[英]How can I customize the unobtrusive validation JQuery messages in ASP NET MVC?
I have a form, and when it does the unobtrusive validtaion I want it to show: 我有一个表单,当它进行不引人注意的验证时,我希望它显示:
This message: "Please enter a value. " 此消息: “请输入值。 ”
Instead of this message: "This Field is required." 而不是这条消息: “此字段是必需的。”
I tried adding this at the end of my jquery.validate.unobtrusive.js file 我尝试在我的jquery.validate.unobtrusive.js文件的末尾添加它
(function ($) {
$.extend($.validator.messages, {
required: "Please enter a value."
});
}(jQuery));
But it's just not working. 但它只是不起作用。
I also trying modifying directly the "messages" variable in jquery.validate.js file but it is not working either. 我也尝试直接修改jquery.validate.js文件中的“messages”变量,但它也无法正常工作。
Could you please tell me how can I get this done? 你能告诉我怎样才能完成这件事?
If you're using the data annotation attributes and don't want to customize the message for each one (which, it appears by one of your comments that this is the case), I can see two options: 如果您正在使用数据注释属性,并且不想为每个属性自定义消息(通过您的一条评论显示这是这种情况),我可以看到两个选项:
1) Create your own data annotation attribute and set a default message, and change all instances of [Required]
to your new attribute. 1)创建自己的数据注释属性并设置默认消息,并将
[Required]
所有实例更改为新属性。
2) You can try it in jQuery: 2)你可以在jQuery中尝试:
// reset the form's validator
$("form").removeData("validator");
// change the text on each required attribute
$(":input[data-val-required]").attr("data-val-required", "Please enter a value");
// reapply the form's validator
$.validator.unobtrusive.parse(document);
I tried this javascript in Chrome's console and everything seemed to work ok. 我在Chrome的控制台中尝试了这个javascript,一切似乎都运行正常。 The reason why you need to do this is because 1) the validation rules are cached by the browser so you need to clear them out (See this answer for more information).
您需要这样做的原因是1)验证规则由浏览器缓存,因此您需要清除它们(有关详细信息,请参阅此答案 )。 And 2) all of the error messages are in the html markup once the page is rendered, so that's where you need to change the validation messages.
2)所有的错误消息是在HTML标记,一旦呈现页面,所以这就是你需要更改验证消息。
Why don't you use ErrorMeesage on validation attrs 为什么不在验证attrs上使用ErrorMeesage
[Required(ErrorMessage="Please enter a value.")]
Edit: From ThisPost , it is another approach: 编辑:从ThisPost ,这是另一种方法:
MyNewResource.resx
. MyNewResource.resx
。 PropertyValueInvalid
with the desired message format (eg "content {0} is invalid for field {1}"). PropertyValueInvalid
(例如,“内容{0}对于字段{1}无效”)。 If you want to change PropertyValueRequired
too add it as well. PropertyValueRequired
也可以添加它。 DefaultModelBinder.ResourceClassKey = "MyNewResource"
to your Global.asax startup code. DefaultModelBinder.ResourceClassKey = "MyNewResource"
到您的Global.asax启动代码中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.