Search code examples
asp.netasp.net-mvc-2asp.net-mvc-2-validation

MVC 2 Model Validation messages


i have a view model with a property like this one :

[RegularExpression(@"^d\+$", ErrorMessageResourceType = typeof(Resources.Validation), ErrorMessageResourceName = "NumberValidationMsg" )]
public int? Number {get; set;}

NumberValidationMsg resource is set to "Only numbers allowed !".

but when I try to enter something like 'test' into Number field on form, ModelState displays the ErrorMessage with content similar to : "The value 'test' is not valid for Number."

can this message be turned off, customized ? (or maybe the best solution would be just to replace int? with string )

Thank You !


Solution

  • If you want to accept text in the field, you need to change it to a string, and make your conversions to int according to your rules.

    If your model is an int, then the only valid input will be int (or empty, if it is "int?"), and you should not try to prevent this unless there are good reasons... Moreover, I believe that you could leave the whole regular expression out, because the MVC already does that check for you implicitly (because it is an int).