1)如何让 jQuery 从资源中获取我想要的消息,而不是默认的“此字段是必需的”,因此它将打印“请输入电子邮件”之类的内容。
随时调用以下内容来覆盖消息。下面的字符串可以用变量替换。
jQuery.extend(jQuery.validator.messages, {
required: "This field is required.",
remote: "Please fix this field.",
email: "Please enter a valid email address.",
url: "Please enter a valid URL.",
date: "Please enter a valid date.",
dateISO: "Please enter a valid date (ISO).",
number: "Please enter a valid number.",
digits: "Please enter only digits.",
creditcard: "Please enter a valid credit card number.",
equalTo: "Please enter the same value again.",
accept: "Please enter a value with a valid extension.",
maxlength: jQuery.validator.format("Please enter no more than {0} characters."),
minlength: jQuery.validator.format("Please enter at least {0} characters."),
rangelength: jQuery.validator.format("Please enter a value between {0} and {1} characters long."),
range: jQuery.validator.format("Please enter a value between {0} and {1}."),
max: jQuery.validator.format("Please enter a value less than or equal to {0}."),
min: jQuery.validator.format("Please enter a value greater than or equal to {0}.")
});
否则,您可以在.validate()
.
$(document).ready(function () {
$('#myform').validate({ // initialize the plugin
rules: {
field1: {
required: true,
minlength: 5
}
},
messages: {
field1: {
required: "custom message for field 1 required",
minlength: "custom message: {0} chars required"
}
}
});
});
演示:http: //jsfiddle.net/XV3ZR/
要在插件首次初始化后动态更改任何消息,需要使用方法覆盖。rules('add')
$('#field1').rules('add', {
messages: {
required: "field 1 required",
minlength: "{0} chars required"
}
});
演示 2:http: //jsfiddle.net/PJGgE/1/
2)如果我更改浏览器语言,如何让 jQuery 自动以另一种语言打印相同的自定义消息?
我不确定您所说的“更改浏览器语言”是什么意思,但同样,上面#1 中的方法是唯一的方法,AFAIK。这些只是字符串,您必须手动或通过外部方法翻译它们。