how to change type validation error messages?

c# data-annotations entity-framework entity-framework-6 validation

Question

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.

1
2
1/19/2018 9:19:51 PM

Accepted Answer

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.

1
1/20/2018 1:13:31 AM

Popular Answer

We can achieve this by different type of validation which is available in the ASP MVC framework.

  1. Data Annotation Validators in “MODEL”
    In Asp.net MVC, we can easily implement validation to application by using Data Annotation attribute to model. Data Annotation attribute classes are present in System.ComponentModel. DataAnnotations namespace. It is a common validation attributes which extend the built-in ASP.NET DataAnnotations (Required, Range, RegularExpression, StringLength etc.,).

  2. Server Side Model Validation
    The ASP.NET MVC server-side validation using the Data Annotation classes. ASP.NET MVC Framework validates the data passed to the controller action and it populate ModelState with validation state based on the success/failure.

You can refer below links also

http://dotnet-helpers.com/mvc/validation-in-mvc4-razor-with-the-data-annotation-validators-in-model/

http://dotnet-helpers.com/mvc/server-side-model-validation-in-mvc-4-razor/



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow