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

前端 未结 5 498
庸人自扰
庸人自扰 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条回答
  •  春和景丽
    2020-12-30 03:57

    After spending a couple of hours looking around, I see no one really has a suitable answer to this. I have found a solution that works for me so I thought I'd post it.

    The problem for me was validating a nullable int. When a non valid value was entered by the user, the default message "The value 'dsfd' is not valid for Issue'.

    The solution I came up with was to remove the errors from the model state and add my own.

    The classes to perform the validation are below:

    [AttributeUsage(AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property, AllowMultiple = false)]
    public class ValidInteger : ValidationAttribute
    {
         protected override ValidationResult IsValid(object value, ValidationContext validationContext)
         {
             if (value == null || value.ToString().Length == 0)
             {
                 return ValidationResult.Success;
             }
             int i;
    
             return !int.TryParse(value.ToString(), out i) ? new ValidationResult(ErrorMessage) : ValidationResult.Success;
         }
    
    }
    
     public class ValidIntegerValidator : DataAnnotationsModelValidator
     {
         public ValidIntegerValidator(ModelMetadata metadata, ControllerContext context, ValidInteger attribute)
             : base(metadata, context, attribute)
         {
             if(!attribute.IsValid(context.HttpContext.Request.Form[attribute.ObjectId]))
             {
                 var propertyName = metadata.PropertyName;
                 context.Controller.ViewData.ModelState[propertyName].Errors.Clear();
                 context.Controller.ViewData.ModelState[propertyName].Errors.Add(attribute.ErrorMessage);
             }
         }
     }
    

    Don't forget you'll also need to register the adapter in the global Application_Start()

    DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(ValidInteger), typeof(ValidIntegerValidator));
    

    And decorate your property with the new attribute

    [ValidInteger(ErrorMessage = "Please enter a valid number for issue")]
    

提交回复
热议问题