16

I have this in my mode:

[Required(AllowEmptyStrings = false, ErrorMessageResourceType = typeof(Registration), ErrorMessageResourceName = "NameRequired")]
[MinLength(3, ErrorMessageResourceType = typeof(Registration), ErrorMessageResourceName = "NameTooShort")]
public String Name { get; set; }

This ends up in:

    <div class="editor-label">
        <label for="Name">Name</label>
    </div>
    <div class="editor-field">
        <input class="text-box single-line" data-val="true" data-val-required="Name is required" id="Name" name="Name" type="text" value="" />
        <span class="field-validation-valid" data-valmsg-for="Name" data-valmsg-replace="true"></span>
    </div>

How come MinLength is being ignored by the compiler? How can I "turn it on"?

caitriona
  • 8,569
  • 4
  • 32
  • 36
Roger Far
  • 2,178
  • 3
  • 36
  • 67

4 Answers4

32

Instead of using MinLength attribute use this instead:

[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]

String Length MSDN

Advantage: no need to write custom attribute

Jim
  • 3,425
  • 9
  • 32
  • 49
dtjmsy
  • 2,664
  • 9
  • 42
  • 62
9

Instead of going through the hassle of creating custom attributes...why not use a regular expression?

// Minimum of 3 characters, unlimited maximum
[RegularExpression(@"^.{3,}$", ErrorMessage = "Not long enough!")]

// No minimum, maximum of 42 characters
[RegularExpression(@"^.{,42}$", ErrorMessage = "Too long!")]

// Minimum of 13 characters, maximum of 37 characters
[RegularExpression(@"^.{13,37}$", ErrorMessage = "Needs to be 13 to 37 characters yo!")]
Joe the Coder
  • 1,775
  • 1
  • 19
  • 22
6

The latest version of ASP.Net MVC now supports MinLength and MaxLength attributes. See the official asp.net mvc page: Unobtrusive validation for MinLengthAttribute and MaxLengthAttribute

Huseyin Yagli
  • 9,896
  • 6
  • 41
  • 50
Josh Mouch
  • 3,480
  • 1
  • 37
  • 34
0

Check this question. Reading the comments it seems that both minlength and maxlenght do not work. So they suggest to use StringLength attribute for maxlenght. I guess you should write a custom attribute for the min legth

for the custom attribute you can do something like this

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class MyMinLengthAttribute : ValidationAttribute
{
  public int MinValue { get; set; }  

  public override bool IsValid(object value)
  {
    return value != null && value is string && ((string)value).Length >= MinValue;
  }
}

Hope it helps

Community
  • 1
  • 1
Iridio
  • 9,213
  • 4
  • 49
  • 71