Vivek Goel
Vivek Goel

Reputation: 24140

Attaching a callback before validation of form

I am using jquery form validation plugin http://docs.jquery.com/Plugins/Validation/validate

How can I set a callback which will be get called before calling it's validation function ? I want to trim the values and some pre-validation.

Upvotes: 0

Views: 1238

Answers (2)

Dave Hollingworth
Dave Hollingworth

Reputation: 3710

Putting @charlietfl's answer into practice, this is what I've done (in case it's useful to anyone):

$.validator.addMethod('trim',
  function(value, element, param) {
    $(element).val($.trim(value));
    return true;
  }
);

$(document).ready(function() {
  $('#my_form').validate({
    rules: {
      name: {
        trim: true,
        required: true
      },
      email: {
        trim: true,
        email: true
      }
    }
  });
});

The first rule trims the value, then you can add additional rules like required or email.

Upvotes: 0

charlietfl
charlietfl

Reputation: 171679

addMethod() lets you create own validation method instead of using predfined ones. Within method do the processing necessary.

For example for trimming you could trim the value, and replace it in field...and test against the trimmmed value. Otherwise using change event handlers on fields would likely help also

http://docs.jquery.com/Plugins/Validation/Validator/addMethod#namemethodmessage

Upvotes: 2

Related Questions