override error message (The value 'xxx' is not valid for Age) when input incorrect data type for input field asp.net mvc

Viewed 29501

I've tried to override error message when input incorrect data type in input field on HTML form. For example I have the model like this.

public class Person
{
    public string FirstName {get;set;}
    public int Age {get;set;}
}

For view, I put text input for Age to get it value.

When type some string in Age text box like 'test' and press submit button. I got this error message

The value 'xxx' is not valid for Age

However, I want to change this message and try many way. There 's nothing effect this message value.

Please could you help me to solve this problem.

5 Answers

I just wanted to show the Range attribute error message so I used the answer from wechel and Christna and changed it so the RangeAttribute is used. After adding the Validator class, only a custom Validator needs to be created and registered in the global.asax as shown in wechel's answer.

You also need to add a validation message with name "FieldRangeValidation" to your resource bundle. In my project it contains the following text: "Value must be between {0} and {1}"

public class ValidIntegerRangeValidator : DataAnnotationsModelValidator<RangeAttribute>
{
    public ValidIntegerRangeValidator(ModelMetadata metadata, ControllerContext context, RangeAttribute attribute)
        : base(metadata, context, attribute)
    {
        try
        {
            if (attribute.IsValid(context.HttpContext.Request.Form[metadata.PropertyName]))
            {
                return;
            }                
        }
        catch (OverflowException)
        {
        }

        var propertyName = metadata.PropertyName;
        context.Controller.ViewData.ModelState[propertyName].Errors.Clear();
        context.Controller.ViewData.ModelState[propertyName].Errors.Add(string.Format(Resources.Resources.FieldRangeValidation, attribute.Minimum, attribute.Maximum));
    }
}
        if (ModelState["Age"].Errors.Count > 0)
        {
            ModelState["Age"].Errors.Clear();
            ModelState["Age"].Errors.Add("<your error message>");
        }
Related