12

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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
parliament
  • 21,544
  • 38
  • 148
  • 238

3 Answers3

26

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")]
David Spence
  • 7,999
  • 3
  • 39
  • 63
  • Hey I just tried this and I can't use 2 it says duplicate attribute! lol I still need a solution :( – parliament Feb 19 '13 at 09:39
  • 1
    Ah. 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? – David Spence Feb 19 '13 at 10:52
  • Good idea :) I used StringLength(int.MaxValue, ErrorMessage = "Minimum") for min and regex for max. thanks again – parliament Feb 21 '13 at 06:06
  • 1
    This fails when there is more than one line [RegularExpression(@"^[\s\S]{5,}$", ErrorMessage = "Minimum 5 characters required")] will make it work for multiple lines – girlcode Feb 05 '15 at 01:58
  • I 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. – Stevieboy84 Feb 26 '19 at 09:57
16

Although it is not separate messages, this is what I did:

[StringLength(30, ErrorMessage = "Must be between {2} and {1} characters long.", MinimumLength = 6)]
Soenhay
  • 3,958
  • 5
  • 34
  • 60
0
[StringLength(800, ErrorMessage = "<img src='/images/icon-info.png' /><p>The {0} must be between {2} and {1} characters long.</p>", MinimumLength = 6)]

This will display an image and also min and max length.