I was working on a project and wanted to validate a form. Since I was already using jQuery, I thought I did validate the form using jQuery itself.

I had heard and read about the validation plugin by Jörn Zaefferer and I decided to use it.

Sure enough its easy to use and for a basic form, its mind blowingly “simple”. But, I wanted more control in form of validating the form for some custom validation rules.

I did some looking around and stumbled on to some posts, docs, etc. and sure enough I could add how the plugin validated each field in the form. But, I still wanted to make it easier to validate, not having to add functions to the validator and again having to add those functions as rules to input controls, I thought I did use regex.

Below is what I used and it’s pretty simple.

199
200
201
202
203
204
205
206
207
208
209
 $.validator.addMethod(
        "custom_rules",
        function(value, element, reg) {
            if (reg.constructor != RegExp)
                reg = new RegExp(reg);
            else if (reg.global)
                reg.lastIndex = 0;
            return this.optional(element) || reg.test(value);
        },
        "Wrong input found, please check your input."
);

Adding this one method to the validator, I was able to add as many rules as I wanted without having to add more methods or functions to the validator class. For e.g. For the text input control accepting phone numbers in the format xxx-xxx-xxxx I used the following rule.

 $("#applicantPhone").rules("add", { custom_rules: /[0-9][0-9][0-9-[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]/ });