Disable "Value" xxx "is invalid for message" yyy "

In my ASP.NET MVC application, I have a form and I am using a ViewModel, so the ModelBinder can bind to my strongly typed class. I am using DataAnnotations to check

public class FormViewModel
{
    [Required]
    public string SomeValue {get;set;}

    [Range(0, 10, ErrorMessage="Enter a number between 0 and 10.")]
    public byte? SomeOtherValue {get;set;}

}

      

This works great. However, the problem is when the user does not enter a valid value for SomeOtherValue (like abc), MVC standard error appears: "The value 'abc' is not valid for 'SomeOtherValue'. This is really annoying as I cannot customize this message. I know that there are ways to localize this message, but that just doesn't make sense (I don't want a generic message, I want a value whose value is).

I tried to apply the RegularExpression attribute to "SomeOtherValue" which only allows byte values, but the standard check is probably "overriding" this check. Is there a way to apply a custom value "value is not valid" to the property or otherwise disable the default message?

+3


source to share


1 answer


Here's another (imperfect way, IMHO) to fix it if the custom validation attribute doesn't work for you. In the controller:



if (!ModelState.IsValid)
{
    string fieldName = "ThatFieldName";
    var m = ViewData.ModelState[fieldName];

    if (m != null && m.Errors.Count > 0)
    {
        ViewData.ModelState.Remove(fieldName);
        ViewData.ModelState.AddModelError(fieldName, "You mucked that field up.");
    }
}

      

0


source







All Articles