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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With