Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 337
parliament Avatar asked Feb 09 '13 04:02

parliament


1 Answers

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")]
like image 101
David Spence Avatar answered Oct 04 '22 01:10

David Spence