Calling built-in validation methods from the jQuery validation plugin inside custom validation methods

We use the validation plugin for jQuery extensively on our site. To make optimal use of the plugin, we wrote a bunch of custom validation methods. Some of these rules actually invoke a built-in validation method that came with the plugin. This is possible because the methods which are available to the plugin are kept in the $.validator.methods object.
Suppose we have the following situation: we have a provider of trainings that requires interested people to enter their phone number when they want to receive more information about the training. Most providers do not require this, so validation of the phone number is dependent on this per-provider setting.

Simply doing the following won’t work, however:

$(document).ready(function() {
    $.validator.addMethod('checkPhone', function (value, element) {
        return !phoneRequired || $.validator.methods.required(value, element);
    });
});

If you run this, the browser will complain that <Object> has no method 'depend'. This is because this inside the required method will now be the methods object instead of the element being validated. Providing the correct value for the this object is straightforward though, using the call function:

$(document).ready(function() {
    $.validator.addMethod('checkPhone', function (value, element) {
        return !phoneRequired || $.validator.methods.required.call(this, value, element);
    });
});
Tagged

One Response to Calling built-in validation methods from the jQuery validation plugin inside custom validation methods

  1. Ionut says:

    Hi, why do you need to call the default method in your custom method and not apply both on that element? That way you can also show different messages for each rule that fails.
    Cheers from etb

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>