Adding custom validations using jQuery Validate
I generally use jquery-validate
plugin for frontend validations. It comes with handful of validator methods. Sometimes we need custom validations. Lets see how to add one.
// Add validator method
$.validator.addMethod("pan", function(value, element) {
return /^[A-Z]{5}[\d]{4}[\A-Z]{1}$/i.test(value);
}, "Please enter a VALID PAN number");
//Use method
rules: {
'inputElementName': {
pan: true
}
}
Tha above code code adds method pan
to the validator plugin, here value
is the value of input element to which validation will be binded and element
is the element itself. We can also pass another parameter, if we need to add some complex validation.
$.validator.addMethod("min", function(value, element, params) {
var selector = params,
minValue = $(selector).val();
return this.optional(element) || value >= minValue;
}, "Please enter value lesser than the given value");
//Use method
rules: {
'inputElementName': {
min: 'inputElementNameSelectorToBeCompared'
}
}
References: jQuery.validator.addMethod()