41

The jQuery Validation plugin works great and is very easy to use:

$(".selector").validate({
})

Just by setting CSS classes like "required email", the default message will be displayed.

However, I need to customize the messages. The documentation says you can specify rules using a key-value pair for elements and their corresponding messages:

$(".selector").validate({
   rules: {
     name: "required",
     email: {
       required: true,
       email: true
     }
   },
   messages: {
     name: "Please specify your name",
     email: {
       required: "We need your email address to contact you",
       email: "Your email address must be in the format of name@example.com"
     }
   }
})

But, it is not practical to specify a rule for every form element, especially server-generated controls in ASP.NET. Is it possible to specify rules that would apply to ALL elements? Or can I use a class selector somehow?

I tried the following, but it didn't work:

$("#frmMyForm").validate
({
    rules:
    {
        $(".required email"):
        {
            required: true,
            email: true
        }
    },
    messages:
    {
        $(".required email"):
        {
            required: "Please enter your email address",
            email: "Your email address must be in the format of name@example.com"
        }
    }
});

That seemed to have a syntax error - the plugin didn't do anything. Then I tried:

$("#frmMyForm").validate
({
    rules:
    {
        ".required email":
        {
            required: true,
            email: true
        }
    },
    messages:
    {
        ".required email":
        {
            required: "Please enter your email address",
            email: "Your email address must be in the format of name@example.com"
        }
    }
});

This didn't have any syntax error - the plugin worked, but it ignored the rules/custom messages. Has anyone here used jQuery Validation plugin? If so, how did you apply rules/custom messages to multiple elements?

Stephen Ostermiller
  • 23,933
  • 14
  • 88
  • 109
Zesty
  • 2,922
  • 9
  • 38
  • 69
  • I guess since we have the source code, I can change the message there. But it would be nice to be able to have different messages for different classes - or a mechanism by which we can have it apply to multiple elements. – Zesty Feb 27 '12 at 08:00
  • Is there anything wrong with the answers so far? – Sparky Feb 28 '12 at 05:27
  • Sorry, I'm still trying them all out. I ran into some unexpected complications related to validation groups (I'll ask that as a separate question). I will close this question today - I always close all questions I ask. Thanks for all your help. – Zesty Feb 28 '12 at 07:20

9 Answers9

79

For the purposes of my example, this is the base starting code:

HTML:

<input type="text" name="field_1" />
<input type="text" name="field_2" />
<input type="text" name="field_3" />

JS:

$('#myForm').validate({
    rules: {
        field_1: {
            required: true,
            number: true
        },
        field_2: {
            required: true,
            number: true
        },
        field_3: {
            required: true,
            number: true
        }
    }
});

DEMO: http://jsfiddle.net/rq5ra/


NOTE: No matter which technique below is used to assign rules, it's an absolute requirement of the plugin that every element has a unique name attribute.


Option 1a) You can assign classes to your fields based on desired common rules and then assign those rules to the classes. You can also assign custom messages.

HTML:

<input type="text" name="field_1" class="num" />
<input type="text" name="field_2" class="num" />
<input type="text" name="field_3" class="num" />

The .rules() method must be called after invoking .validate()

JS:

$('#myForm').validate({
    // your other plugin options
});

$('.num').each(function() {
    $(this).rules('add', {
        required: true,
        number: true,
        messages: {
            required:  "your custom message",
            number:  "your custom message"
        }
    });
});

DEMO: http://jsfiddle.net/rq5ra/1/

Option 1b) Same as above, but instead of using a class, it matches a common part of the name attribute:

$('[name*="field"]').each(function() {
    $(this).rules('add', {
        required: true,
        number: true,
        messages: { // optional custom messages
            required:  "your custom message",
            number:  "your custom message"
        }
    });
});

DEMO: http://jsfiddle.net/rq5ra/6/


Option 2a) You can pull out the groups of rules and combine them into common variables.

var ruleSet1 = {
        required: true,
        number: true
    };

$('#myForm').validate({
    rules: {
        field_1: ruleSet1,
        field_2: ruleSet1,
        field_3: ruleSet1
    }
});

DEMO: http://jsfiddle.net/rq5ra/4/


Option 2b) Related to 2a above but depending on your level of complexity, can separate out the rules that are common to certain groups and use .extend() to recombine them in an infinite numbers of ways.

var ruleSet_default = {
        required: true,
        number: true
    };

var ruleSet1 = {
        max: 99
    };
$.extend(ruleSet1, ruleSet_default); // combines defaults into set 1

var ruleSet2 = {
        min: 3
    };
$.extend(ruleSet2, ruleSet_default); // combines defaults into set 2

var ruleSet3 = { };
$.extend(ruleSet3, ruleSet1, ruleSet2); // combines sets 2 & 1 into set 3.  Defaults are included since they were already combined into sets 1 & 2 previously.

$('#myForm').validate({
    rules: {
        field_1: ruleSet2,
        field_2: ruleSet_default,
        field_3: ruleSet1,
        field_4: ruleSet3
    }
});

End Result:

  • field_1 will be a required number no less than 3.
  • field_2 will just be a required number.
  • field_3 will be a required number no greater than 99.
  • field_4 will be a required number between 3 and 99.

DEMO: http://jsfiddle.net/rq5ra/5/

Sparky
  • 98,165
  • 25
  • 199
  • 285
25

You could use addClassRules, like:


jQuery.validator.addClassRules("name", {
  required: true,
  minlength: 2
});

Sudhir Bastakoti
  • 99,167
  • 15
  • 158
  • 162
19

jQuery.validator.addClassRules(); will attach the validation to class, but there is no option for messages, it will use the general error messages.

If you want that to work then, you should refactor the rules like this

$.validator.addMethod(
     "newEmail", //name of a virtual validator
     $.validator.methods.email, //use the actual email validator
     "Random message of email"
);

//Now you can use the addClassRules and give a custom error message as well.
$.validator.addClassRules(
   "email", //your class name
   { newEmail: true }
 );
Starx
  • 77,474
  • 47
  • 185
  • 261
  • Your answer solved my problem today. for the case when you do not have fix number of elements and very depending upon some factor at that this solution is very helpful – Rajan Rawal Jun 20 '13 at 05:25
0

Alternative approach:

$.validator.addMethod("cMaxlength", function(value, element, param) {
  
 return $.validator.methods.maxlength.call(this, value, element, param[1]);

}, '{0}');

Gist: https://gist.github.com/uhtred/833f3b957d61e94fbff6

$.validator.addClassRules({
    'credit-card': {
     cMaxlength: [ 'Invalid number.', 19 ]
    }
});
0

$.validator.addMethod("cMaxlength", function(value, element, param) {
  
 return $.validator.methods.maxlength.call(this, value, element, param[1]);

}, '{0}');
Jaimin Soni
  • 1,061
  • 1
  • 13
  • 29
0

I've built upon Starx's answer to create a repeatable easy to use function that uses the default methods and creates new error messages for specific classes. considering the fact that your specific class will only be used to override the message once you shouldn't have any conflicts reusing this for many different class names using any existing methods.

var CreateValidation = function(className, customMessage, validationMethod){
  var objectString = '{"'+ className +'": true}',
  validator = $.validator;

  validator.addMethod(
    className,
    validator.methods[validationMethod],
    customMessage
  );
  validator.addClassRules(
    className,
    JSON.parse(objectString)
  );
};

Usage Example with validation class being "validation-class-firstname":

CreateValidation('validation-class-firstname', 'Please enter first name', 'required');
0

You can add class rules using the addClassRules method:

E.g.

$.validator.addClassRules("your-class", {
  required: true,
  minlength: 2
});

https://jqueryvalidation.org/jQuery.validator.addClassRules/

user3539640
  • 11
  • 1
  • 2
0

$.validator.addMethod("cMaxlength", function(value, element, param) {
  
 return $.validator.methods.maxlength.call(this, value, element, param[1]);

}, '{0}');
-1

Before this you have to include Query file

$("#myform_name").validate({
    onfocusout: function(element) { $(element).valid(); } ,
    rules:{
       myfield_name: {
          required:true
       },
       onkeyup: false,
       messages: {
          myoffer: "May not be empty"
       }
    }
});
2Yootz
  • 3,971
  • 1
  • 36
  • 31
dev4092
  • 2,820
  • 1
  • 16
  • 15
  • Your answer is an exact copy, word for word of [this one](http://stackoverflow.com/a/19678178/594235). Beside being a duplicate answer, it's not an answer at all. Obviously the jQuery file was already included when the OP said this, _"The jQuery Validation plugin works great"_. – Sparky Jul 02 '14 at 15:35