开发者

jQuery form validation logic

开发者 https://www.devze.com 2023-04-07 11:53 出处:网络
I have the following code: function showError(l, msg) { $(\'#\'+l).css({\'color\':\'red\'}); $(\'#error\').html(msg).fadeIn(500);

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号