S.P. S.P. - 1 year ago 79
jQuery Question

How to add multiple methods for one field in jQuery validate

Can jQuery validate plugin pass multiple methods through one field?

for example, add two methods:

var num1 = 1;
num2 = 10;
range1 = 100;
range2 = 250;
value = $("#something_from_html")

$.validator.addMethod("method_one", function( value, element ) {
if(value < num1 || value > num2)
return false;
return method_one(value, num1, num2);
}, I18N("wrong number"));

$.validator.addMethod("method_two", function( value, element ) {
if( value < range1 || value > range2)
return false;
return method_two(value, range1, range2);
}, I18N("wrong range"));

and return different warning message to one field:

$("#form").each(function(index, el) {
rules: {
something_from_html: {
required: true,
method_one: true,
method_two: true


the HTML part:

<form id="form" name="form">
<input type="text" name="something_from_html" id="something_from_html">

When I add one method to rule, it works perfectly. But when I add both of method_one and method_two, it doesn't work. Anybody know how to fix it?

Answer Source

The issue is due to the logic in your additional methods; they need to return a boolean indicating the validity of the entered value.
Currently they attempt to call a global method with their defined validator method name which doesn't exist.

You also need to use parseInt() to convert the text value entered in to the input to an integer so that it can be compared to your num and range values. Also, those variables should be declared within the validator methods to save any scoping problems.
Try this:

$.validator.addMethod("method_one", function(value, element) {
    var num1 = 1, num2 = 10;
    value = parseInt(value, 10);
    return !(value < num1 || value > num2);
}, I18N("wrong number"));

$.validator.addMethod("method_two", function(value, element) {
    var range1 = 100, range2 = 250;
    value = parseInt(value, 10);
    return !(value < range1 || value > range2);
}, I18N("wrong range"));

Working example