jQuery validation plugin: Rules
I was working on a project and wanted to validate a form. Since I was already using and including 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, yes there is a but, but on the good side..
But, being a control freak, I wanted more control in form of validating the form, my way. I did some looking around and stumbled on to some posts, docs, etc. and sure enough I could add how the plugin validate 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 – an ol’ friend, to help me.
Below is what I used and it’s pretty simple.
$.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]/ });
Simple isn’t it? Offcourse, I have used much simpler regex in the form
Please Note:
As mentioned on the Validations Plugins documentation for the addMethod, it is cleaner to wrap regex in their own functions per ".selector" or input objects. For more on regex and more on this note.Hi Ravinder,
Yes its possible to have custom validations.. but you will have add validation methods to the validator. For more Look here http://www.swartzfager.org/thoughts/post.cfm/custom-jquery-validate-rule-for-making-sure-one-date-is-later-than-another
umm it aint working please check once the demo url
Sent you an email with screenshots. Do you have a url online where I can check whats up?
awesome thanks
pleasure
umm any Demo for this please..
i would really need a demo for this i have some problems
Hey MR52,
added a demo link and mailed you the same too, thanks!















Every website I design/develop, I follow some essential steps to make your time and investment count. From free consultation to free post-production support. 
Author: RAVINDER
plzz help me..can we use if condition in jquery validation like:
$().ready(function()
{
$(”#signupForm”).validate(
{
rules: {
element_19:
{ required: true,
if($(’#event’).val()==’8′)
{ other: “required”
}
else{ //no }
……………………
plzz help me..