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

前端 未结 5 502
庸人自扰
庸人自扰 2020-12-30 03:15

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         


        
5条回答
  •  Happy的楠姐
    2020-12-30 03:52

    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
    {
        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));
        }
    }
    

提交回复
热议问题