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

26,448

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)]
Share:
26,448
parliament
Author by

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, 2022

Comments

  • parliament
    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 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.

  • parliament
    parliament over 11 years
    Hey I just tried this and I can't use 2 it says duplicate attribute! lol I still need a solution :(
  • David Spence
    David Spence over 11 years
    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?
  • parliament
    parliament over 11 years
    Good idea :) I used StringLength(int.MaxValue, ErrorMessage = "Minimum") for min and regex for max. thanks again
  • girlcode
    girlcode over 9 years
    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
  • CooncilWorker
    CooncilWorker about 8 years
    If you don't use [Required] and the string is empty, then MinimumLength is ignored.
  • Stevieboy84
    Stevieboy84 about 5 years
    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.