3

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 false;
  }
  // 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

1
  • 3
    Is there a reason you don't use the jQuery Validation plugin? It makes this type of thing super easy. Commented Sep 26, 2011 at 17:56

1 Answer 1

4

Use the jQuery Validation Plugin.

http://bassistance.de/jquery-plugins/jquery-plugin-validation/

It does this type of thing without writing any code.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.