Separate error message for Minimum and Maximum string length - MVC4 Data annotation
Solution 1
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")]
Solution 2
Although it is not separate messages, this is what I did:
[StringLength(30, ErrorMessage = "Must be between {2} and {1} characters long.", MinimumLength = 6)]
parliament
Serial Entrepreneur Full Stack Developer (C#/AngularJS/D3.js) Contact me if you want to work on cool shit with me. Currently in the bitcoin space, starting a cryptocurrency exchange. Also have a body of work on automated trading systems. [email protected]
Updated on July 09, 2022Comments
-
parliament almost 2 years
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 aMinLength
/MaxLength
do not generate unobtrusive validation markup as they are notIClientValidatable
Although this seems like a very common requirement I cannot find an implementation on the web.
-
parliament over 11 yearsHey I just tried this and I can't use 2 it says duplicate attribute! lol I still need a solution :(
-
David Spence over 11 yearsAh. I knew they worked unobtrusively... What about using one of these for the minimum and
[StringLength(50, ErrorMessage = "Maximum {2} characters exceeded")]
for the max? -
parliament over 11 yearsGood idea :) I used StringLength(int.MaxValue, ErrorMessage = "Minimum") for min and regex for max. thanks again
-
girlcode over 9 yearsThis fails when there is more than one line [RegularExpression(@"^[\s\S]{5,}$", ErrorMessage = "Minimum 5 characters required")] will make it work for multiple lines
-
CooncilWorker about 8 yearsIf you don't use [Required] and the string is empty, then MinimumLength is ignored.
-
Stevieboy84 about 5 yearsI personally don't think this is an appropriate answer, given that you may already be using a regex for something else (in my case a password field with a regex to check for specific characters). I think the right approach is probably to extend StringLength or create your own attribute.