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.
(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);
$this.val() === ''
as it is true if$this.val().length < 3
is true. \$\endgroup\$