数据标注更改验证消息 [英] change validate message in data annotation
问题描述
我的对象与数据类型为int场。当我把HTML格式的文本框这封信没有编号声言如下─领域必须是数字验证器。我怎样才能改变这样此次的消息
[必需(的ErrorMessage =Введитеназвание)]
[DisplayName的(Название)]
公众诠释年龄{搞定;组; }
我还没有找到一个的清洁的方式实现这一目标使用数据注释。一种方法是编写自定义模型绑定,但是这似乎是一个大量的工作,对于这样一个简单的任务做。
要实现这个另一种方式是一个 App_GlobalResources文件
文件夹添加到您的ASP.NET应用程序。添加一个名为 Messages.resx
包含 PropertyValueRequired
字符串资源。资源文件
PropertyValueRequired =一些自定义错误消息
在你的的Application_Start
注册资源类键:
保护无效的Application_Start()
{
的RegisterRoutes(RouteTable.Routes);
DefaultModelBinder.ResourceClassKey =消息;
}
请注意,ASP.NET MVC 2使用 PropertyValueInvalid
而不是 PropertyValueRequired
资源键。
IMO使用数据注释来执行验证逻辑是有限的(也许在.NET 4中,这将改变)。如果你想有过验证逻辑,我会建议你使用验证库,如流利的验证<完全控制/ A>或 XVAL 。
my object has field with data type int. when i put in html form in this textbox letter not number the validator say- The field must be a number. how can i change this messages like this
[Required(ErrorMessage = "Введите название")]
[DisplayName("Название")]
public int age { get; set; }
I haven't found a clean way to achieve this using Data Annotations. One way would be to write a custom model binder but this seems like a lot of work to do for such a simple task.
Another way to achieve this is to add an App_GlobalResources
folder to your ASP.NET application. Add a resource file called Messages.resx
containing a PropertyValueRequired
string resource.
PropertyValueRequired = "Some custom error message"
In your Application_Start
register the resource class key:
protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
DefaultModelBinder.ResourceClassKey = "Messages";
}
Note that ASP.NET MVC 2 uses the PropertyValueInvalid
instead of PropertyValueRequired
resource key.
IMO using Data Annotations to perform validation logic is limited (maybe in .NET 4 this will change). If you want to have full control over the validation logic I would recommend you using a validation library such as Fluent Validation or xVal.
这篇关于数据标注更改验证消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!