mrjayviper
mrjayviper

Reputation: 2388

jQuery validation plugin. How can I have 1 message for several rules?

This is a snippet of javascript code

$("#myform").validate({
    rules: {
        "studentid": {
            required: true
            , digits: true
            , maxlength: 7
            , minlength: 7
        }

I would like to have 1 message for required, digits, maxlength and minlength rules. I want this text to display: "Invalid format"

I know I can specify a message for each rule individually like:

  messages: {
    name: {
      required: "We need your email address to contact you",
      minlength: jQuery.validator.format("At least {0} characters required!")
    }
  }

But is it possible to have a shortcut? thanks! :)

Upvotes: 0

Views: 452

Answers (2)

Sparky
Sparky

Reputation: 98718

I would like to have 1 message for required, digits, maxlength and minlength rules. I want this text to display: "Invalid format"

You are allowed to assign a single message to the field and it will apply to all rules for that field...

$("#myform").validate({
    rules: {
        studentid: {
            required: true,
            digits: true,
            maxlength: 7,
            minlength: 7
        }
    },
    messages: {
        studentid: "Invalid Format"  // same message for all rules on this field
    }
});

DEMO: jsfiddle.net/4xayL7bk/

Upvotes: 1

Mayank Pandeyz
Mayank Pandeyz

Reputation: 26258

You can achieve this like:

var errorMsg = "Invalid Format";

messages: {
    name: {
      required: errorMsg,
      minlength: errorMsg
    }
  }

Upvotes: 1

Related Questions