Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change 'data-val-number' message validation in MVC while it is generated by @Html helper

Assume this model:

Public Class Detail     ...     <DisplayName("Custom DisplayName")>     <Required(ErrorMessage:="Custom ErrorMessage")>     Public Property PercentChange As Integer     ... end class 

and the view:

@Html.TextBoxFor(Function(m) m.PercentChange) 

will proceed this html:

   <input data-val="true"      data-val-number="The field 'Custom DisplayName' must be a number."      data-val-required="Custom ErrorMessage"          id="PercentChange"      name="PercentChange" type="text" value="0" /> 

I want to customize the data-val-number error message which I guess has generated because PercentChange is an Integer. I was looking for such an attribute to change it, range or whatever related does not work.
I know there is a chance in editing unobtrusive's js file itself or override it in client side. I want to change data-val-number's error message just like others in server side.

like image 789
GtEx Avatar asked Jan 28 '11 12:01

GtEx


People also ask

Which component of MVC controller can be used to find dictionary of validation error?

ASP.NET MVC: ValidationSummary The ValidationSummary() extension method displays a summary of all validation errors on a web page as an unordered list element. It can also be used to display custom error messages.


2 Answers

You can override the message by supplying the data-val-number attribute yourself when rendering the field. This overrides the default message. This works at least with MVC 4.

@Html.EditorFor(model => model.MyNumberField, new { data_val_number="Supply an integer, dude!" })

Remember that you have to use underscore in the attribute name for Razor to accept your attribute.

like image 81
HenningJ Avatar answered Sep 28 '22 05:09

HenningJ


What you have to do is:

Add the following code inside Application_Start() in Global.asax:

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

Right click your ASP.NET MVC project in VS. Select Add => Add ASP.NET Folder => App_GlobalResources.

Add a .resx file called Messages.resx in that folder.

Add these string resources in the .resx file:

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. 

Change the FieldMustBeNumeric value as you want... :)

You're done.


Check this post for more details:

Localizing Default Error Messages in ASP.NET MVC and WebForms

like image 20
Leniel Maccaferri Avatar answered Sep 28 '22 04:09

Leniel Maccaferri