Separate error message for Minimum and Maximum string length – MVC4 Data annotation

asp.net-mvc-4data-annotationsvalidation

Would someone please share their implementation of having separate error messages for minimum and maximum string length using data annotations in MVC?

It seems StringLength only allows a single error message a MinLength/MaxLength do not generate unobtrusive validation markup as they are not IClientValidatable

Although this seems like a very common requirement I cannot find an implementation on the web.

Best Answer

You can use the RegularExpression data annotation for the minimum check and use the StringLength attribute for the maximum check. Javascript will execute regular expressions client side so they are nice and unobtrusive! You can only use one RegularExpression attribute per property, otherwise you could do both maximum and minimum using regular expression.

Minimum of 5 characters

[RegularExpression(@"^.{5,}$", ErrorMessage = "Minimum 5 characters required")]

Maximum of 50 characters

[StringLength(50, ErrorMessage = "Maximum {2} characters exceeded")]