jQuery form validation logic
I have the following code:
function showError(l, msg) {
$('#'+l).css({'color':'red'});
$('#error').html(msg).fadeIn(500);
}
$(document).ready(function(){
$('#form').submit(function() {
if($('#username').val() == '') {
showError('labelUser', 'Please enter a username');
return false;
}
if($('input[type=password]')[0].value != $('input[type=password]')[1].value) {
showError('labelPassword', 'Password does not match');
return f开发者_C百科alse;
}
// etc...
$('label').css({'color':'black'});
$('#error').html('').fadeOut(200);
return true;
});
});
I have in my form a total of 10 fields (name, first name, email etc...). As you can see in my script (//etc...
), I repeat the SAME case over and over if a field is valid or not.
I think repeating the showError
and return false
is not a good solution.
Is there an easier way (or better) to use validate data? Thank you
Use the jQuery Validation Plugin.
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
It does this type of thing without writing any code.
精彩评论