Search code examples
jqueryjquery-validate

Specifiy the order of the validators in jQuery validate plugin


I'm wondering if it's possible to specify the order in which the validators are run.

Currently I wrote a custom validator that check if it's [a-zA-Z0-9]+ to make sure the login validates our rules and a remote validator to make sure that the login is available but currently the remote validator is lauched before my custom validator. I would like to launch the remote validator only if the element validates my custom validator.

Any clue ?

thanks for reading


Solution

  • You need to augment/monkey patch/overwrite (whichever term makes the most sense to you) the $.fn.rules that the validate plugin uses when creating the rules to run for a field to push your rule to second place in the rules object, after the required rule.

    If you search for rules in the script, you'll need to add similar logic to this just before if (data.required)

    If (data.yourRuleName) {
        var param = data.yourRuleName;
        delete data.yourRuleName;
        data = $.extend({ yourRuleName: param }, data);
    }
    

    Or you can copy the rules section out, add the above and put it in a script that is referenced after the validate script. This way, if the script changes, you won't have to go applying these changes to the new version of the script (assuming that rules would still work the same way).