I am new to asp.net and I have a problem. When the users insert in a editor for a decimal field something other than numbers, they get an error "Field name" is not a number. But I don't want them to receive this message I want them to receive another message. I have no problem with this with required and range validators. Is there any way for me to do this?
I am not refering necessarily to changing the culture just displaying another message.
Thanks.
This validation can be added for both the client side and the server side. You understand that decorating the properties in a model with an Attribute can make that property eligible for Validation. Some of the DataAnnotation used for validation are given below. Required. Specify a property as required.
You can provide a custom error message either in the data annotation attribute or in the ValidationMessageFor() method.
You can use the standard ASP.NET MVC ValidationSummary method to render a placeholder for the list of validation error messages. The ValidationSummary() method returns an unordered list (ul element) of validation messages that are in the ModelStateDictionary object.
Hope I understand your, to change RangeValidator
ErrorMessage
just initialize ErrorMessage
parameter:
[Range(0, 100, ErrorMessage = "Some another error message insert here!")]
[RegularExpression("\d", ErrorMessage = "!!!")]
public decimal DecimalField { get; set; }
This is the actual answer:
Create a class CustomClientDataTypeModelValidatorProvider
. Copy the code from the MVC sources. Change the method MakeErrorString
to output the appropiate message like this:
private static string MakeErrorString(string displayName)
{
return string.Format(
CultureInfo.CurrentCulture,
Core.Resources.Errors.EroareNuENr,
displayName);
}
I couldn't find a way not to copy the code just extend it as it uses this static method. If anyone knows this please tell me.
Then, in global.asax, I wrote this:
var cdProvider = ModelValidatorProviders.Providers.SingleOrDefault(p => p.GetType().Equals(typeof(ClientDataTypeModelValidatorProvider)));
if(cdProvider != null)
{
ModelValidatorProviders.Providers.Remove(cdProvider);
ModelValidatorProviders.Providers.Add(
new CustomClientDataTypeModelValidatorProvider());
}
so that the flow would actually be routed to my class and not the class in the asp.net MVC dll
I got the idea from here:
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