The field must be a number. How to change this message to another language?

依然范特西╮ 提交于 2019-11-28 15:49:44

问题


How can I change that messages for all int fields so that instead of saying:

The field must be a number in English, it shows:

El campo tiene que ser numerico in Spanish.

Is there are a way?


回答1:


If you happen to be using ASP.NET MVC 4 onwards, check this post:

Localizing Default Error Messages in ASP.NET MVC and WebForms

Basically you have to add the following piece of code in your Application_Start() method in Global.asax:

 ClientDataTypeModelValidatorProvider.ResourceClassKey = "Messages";
 DefaultModelBinder.ResourceClassKey = "Messages";

Right click your ASP.NET MVC project in Solution Explorer inside Visual Studio and select Add => Add ASP.NET Folder => App_GlobalResources.

Now add a .resx file inside this folder called Messages.resx.

Finally add the following string resources in that .resx file:

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.

You should be good to go.

Note that the value you're interested in is the FieldMustBeNumeric. To localize it to Spanish, you have to add another resource file named Messages.es.resx. In this specific .resx file replace the resource value with:

Name                Value
====                =====
FieldMustBeNumeric  El campo {0} tiene que ser numerico.

If you happen to be using ASP.NET MVC 3 downwards, this solution can help you achieve the same result: https://stackoverflow.com/a/2551481/114029




回答2:


you can set your custom message for your validation.

 [RegularExpression("\d{9}",ErrorMessage="El campo tiene que ser numerico")]
 public decimal UnitPrice { get; set; } 



回答3:


If you want to specify custom message for each Integer , double and float . you can use Range Attribute with String as below.

    [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; }

Now as above you can specify custom message for each and every propery .



来源:https://stackoverflow.com/questions/12099466/the-field-must-be-a-number-how-to-change-this-message-to-another-language

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!