0

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! :)

mrjayviper
  • 2,258
  • 11
  • 46
  • 82

2 Answers2

1

You can achieve this like:

var errorMsg = "Invalid Format";

messages: {
    name: {
      required: errorMsg,
      minlength: errorMsg
    }
  }
Mayank Pandeyz
  • 25,704
  • 4
  • 40
  • 59
  • thanks for the answer but that's not what I had in mind... I'm still specifying the rules individually. I want to avoid that. :) – mrjayviper Aug 17 '16 at 04:16
  • Check this: http://stackoverflow.com/questions/13716649/using-jquery-validate-plugin-to-output-a-single-error-message-for-multiple-field It will help you in achieving this. – Mayank Pandeyz Aug 17 '16 at 04:40
1

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/

Sparky
  • 98,165
  • 25
  • 199
  • 285