Would like some assistance in improving my jQuery validation code. I have some repeated code, but I am not sure how to write it in a way so that I don't have to keep repeating the same code over and over again for different variable names etc... (such as the if statement part) My goal is to make it so that I can easily apply it to any other form I create.
Javascript:
(function($) {
$('.commentForm').submit(function () {
var error = 'error';
var name = $(this).find('.name')
nameVal = name.attr('value')
email = $(this).find('.email')
comment = $(this).find('textarea')
commentVal = comment.html();
if (!(name.val() === nameVal || name.val() === '' || name.val().length < 3) &&
!(comment.val() === commentVal || comment.val() === '' || comment.val().length < 3) &&
validateEmail(email.val())
) {
console.log('Form is good');
return true;
} else {
(name.val() === nameVal || name.val() === '' || name.val().length < 3) ? name.addClass(error) : name.removeClass(error);
(comment.val() === commentVal || comment.val() === '' || comment.val().length < 3) ? comment.addClass(error) : comment.removeClass(error);
(!validateEmail(email.val())) ? email.addClass(error) : email.removeClass(error);
console.log('Form is BAD');
return false;
}
});
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
}) (jQuery);
Thanks for your help in advance!
UPDATE CODE: (SAME FUNCTIONALITY)
$('form.requiredFields').submit(function(e) {
var req = $(this).find('.req'),
validateEmail = function(email) {
var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
};
req.each(function() {
var $this = $(this),
defaultVal = $this.prop('defaultValue');
if ( ( $this.hasClass('email') && !validateEmail( $this.val() ) ) || (defaultVal === $this.val() || $this.val() === '' || $this.val().length < 3) ) {
$this.addClass('_error')
} else {
$this.removeClass('_error req');
}
});
console.log(req.length);
if ( req.length === 0 ) {
return true;
} else {
return false;
}
});
$this.val() === ''
as it is true if$this.val().length < 3
is true. – Daniel Cook Nov 20 '13 at 14:24