Well I just finished my first go at my own form validation (I always used validate plugin) for simple front end. It's definitely small potatoes as it's only meant for a form with 4 fields; 3 required text and one required e-mail.
I'm new to Jquery so I am doing little exercises like these to help me learn and I was hoping someone could take a look and see if what I did was ok. Did I make any newbie mistakes? Can I improve this? Perhaps I should use js objects (new to those too) to organize code? I know there is no one answer, in fact I'm sure there are countless ways to validate a form...But I was just hoping some JS expert could offer a little insight on better coding practices.
*EDIT - forgot to mention...I'm aware that I should probably use regex for better email validation, however, just threw the indexOf() method for the time being *
$(function() {
var err = "<span class='error'>Required field.</span>";
var errEmail = "<span class='error'>Please enter valid email.</span>";
var errors = false;
$('.submit').click(function() {
$('.error').remove();
$('.req').each(function() {
if($(this).val() == '') {
$(this).after(err);
errors = true;
}
});
if ($('.reqe').val().indexOf('@') === -1) {
$('.reqe').after(errEmail);
errors = true;
}
if (errors == true) {
return false;
}
else {
var errors = false;
alert("Submitted");
return true;
}
});
});
Any feedback would be greatly appreciated. Thanks