A Thunderbolt for a developer! Do you know any good developers based in The Netherlands? Tell them about working at Springest. If we hire them, you will get a 27" Apple Thunderbolt Display. :)

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:

1
2
3
4
5
$(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:

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

Comments