Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 292
Mike Avatar asked May 12 '26 07:05

Mike


1 Answers

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.

like image 156
Cinchoo Avatar answered May 14 '26 22:05

Cinchoo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!