如何在 jQuery 验证器中为一条规则添加一条自定义消息并为所有其他规则添加默认消息

How to add one custom message for one rule and default message for all other rules at jQuery validator

我想为一个规则显示自定义消息,为所有其他规则显示默认消息。例如:

$("#form").validate({
        rules: {
            "ref": {
                required: true,
                minlength: 5,
                maxlength: 5,
                number: true
            }
        },
        messages: {
            "ref": {
                required: "Please, enter a reference",
                default: 'Please enter exact 5 numbers only'
            }
        }
   });

但是,它不起作用。如果我为所有其他规则重复消息,它会起作用,例如:

messages: {
   "ref": {
      required: "Please, enter a reference",
      minlength: 'Please enter exact 5 numbers only',
      maxlength: 'Please enter exact 5 numbers only',
      number: 'Please enter exact 5 numbers only'
    }
}

为所有其他规则重复消息是实现此目的的唯一方法还是有更好的方法?

$("#form").validate({
        rules: {
            "ref": {
                required: true,
                minlength: 5,
                maxlength: 5,
                number: true
            }
        },
        messages: {
            "ref": {
                required: "Please, enter a reference",
                default: 'Please enter exact 5 numbers only'
            }
        },
        submitHandler: function (form) { // for demo
            console.log('valid form submitted'); // for demo
            return false; // for demo
        }
    });
body {
    padding: 20px;
}

label {
    display: block;
}

input.error {
    border: 1px solid red;
}

label.error {
    font-weight: normal;
    color: red;
}

button {
    display: block;
    margin-top: 20px;
}
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/jquery.validate.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/additional-methods.js"></script>

<form id="form" method="post" action="#">
    <label for="name">Reference</label>
    <input type="text" name="ref" id="ref" />
    <button type="submit">Submit</button>
</form>

您可以提供如下默认消息,这将适用于所有验证(此处,number 规则的消息是静态的,maxlengthminlength 消息将是动态的):

jQuery.extend(jQuery.validator.messages, {
    number: "Please enter exact 5 numbers only",
    maxlength: jQuery.validator.format("Please enter exact {0} numbers only."),
    minlength: jQuery.validator.format("Please enter exact {0} numbers only."),
});

另一个建议是取一个变量

str = "Please enter exact 5 numbers only"

并使用它发消息:

messages: {
   "ref": {
      required: "Please, enter a reference",
      minlength: str,
      maxlength: str,
      number: str
    }
}