Search code examples
c#entity-frameworkvalidationentity-framework-6data-annotations

how to change type validation error messages?


I'm using entity framework code first in an ASP MVC project, and I'd like to change the error message that appears for validation of a numeric type.

I have a property like

public decimal Amount1 { get; set; }

If I enter a non-number in the field, I get the message: The field Amount1 must be a number. How do I change that message?

For other validations, like Required I can just use the ErrorMessage parameter like: [Required(ErrorMessage = "My message...")]

Is there something similar for validating types?

Thank you.


Solution

  • Unfortunately Microsoft didn't expose any interfaces to change the default messages.

    But if you are desperate enough to change these non friendly messages, you can do so by creating validation attribute for decimal, creating corresponding validator and finally register it with DataAnnotationsModelValidatorProvider at the application startup. Hope this helps.

    UPDATE:

    Sample below

    Step 1: Create validation attribute

    [AttributeUsage(AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property, AllowMultiple = false)]
    public class ValidDecimalAttribute : ValidationAttribute
    {
        protected override ValidationResult IsValid(object value, ValidationContext validationContext) {
            if (value == null || value.ToString().Length == 0) {
                return ValidationResult.Success;
            }
            decimal d;
            return !decimal.TryParse(value.ToString(), out d) ? new ValidationResult(ErrorMessage) : ValidationResult.Success;
        }
    }
    

    Step 2: Create validator

    public class ValidDecimalValidator : DataAnnotationsModelValidator<ValidDecimal>
    {
        public ValidDecimalValidator(ModelMetadata metadata, ControllerContext context, ValidDecimal attribute)
            : base(metadata, context, attribute)
        {
            if (!attribute.IsValid(context.HttpContext.Request.Form[metadata.PropertyName]))
            {
                var propertyName = metadata.PropertyName;
                context.Controller.ViewData.ModelState[propertyName].Errors.Clear();
                context.Controller.ViewData.ModelState[propertyName].Errors.Add(attribute.ErrorMessage);
            }
        }
    }
    

    Step 3: Register the adapter in Global.asax under Application_Start() method or Main() method

    DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(ValidDecimal), typeof(ValidDecimalValidator));
    

    Step 4: Finally decorate your property in your model with this attribute

    [ValidDecimal(ErrorMessage = "Only decimal numbers allowed")]
    public decimal CPEHours { get; set; }
    

    Hope it helps.