如何更改所有int
字段的消息,而不是说:
The field must be a number
英文,显示:
El campo tiene que ser numerico
。
有办法吗?
答案 0 :(得分:62)
如果您正好使用ASP.NET MVC 4,请查看以下帖子:
Localizing Default Error Messages in ASP.NET MVC and WebForms
基本上,您必须在Application_Start()
的{{1}}方法中添加以下代码:
Global.asax
在Visual Studio内的解决方案资源管理器中右键单击您的ASP.NET MVC项目,然后选择 ClientDataTypeModelValidatorProvider.ResourceClassKey = "Messages";
DefaultModelBinder.ResourceClassKey = "Messages";
。
现在在此文件夹中添加一个名为Add => Add ASP.NET Folder => App_GlobalResources
的{{1}}文件。
最后在.resx
文件中添加以下字符串资源:
Messages.resx
你应该好好去。
请注意,您感兴趣的值是.resx
。要将其本地化为西班牙语,您必须添加另一个名为Name Value
==== =====
FieldMustBeDate The field {0} must be a date.
FieldMustBeNumeric The field {0} must be a number.
PropertyValueInvalid The value '{0}' is not valid for {1}.
PropertyValueRequired A value is required.
的资源文件。在此特定FieldMustBeNumeric
文件中,将资源值替换为:
Messages.es.resx
如果您正好向下使用ASP.NET MVC 3,此解决方案可以帮助您获得相同的结果:https://stackoverflow.com/a/2551481/114029
答案 1 :(得分:6)
您可以设置自定义消息以进行验证。
[RegularExpression("\d{9}",ErrorMessage="El campo tiene que ser numerico")]
public decimal UnitPrice { get; set; }
答案 2 :(得分:0)
如果要为每个Integer指定自定义消息,请双倍并浮动。你可以使用Range Attribute with String,如下所示。
[Required(ErrorMessageResourceType = typeof(Global), ErrorMessageResourceName = "YearOfEstablishmentRequired")]
[Range(0, int.MaxValue, ErrorMessageResourceType = typeof(Global), ErrorMessageResourceName = "ValidYearOfEstablishment")]
[Display(Name = "Year Of Establishment")]
public string YearOfEstablishment { get; set; }
现在,如上所述,您可以为每个属性指定自定义消息。