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.
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")]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With