Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC3 jquery validation MinLength filter not working

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"?

like image 397
Roger Far Avatar asked Aug 25 '11 09:08

Roger Far


2 Answers

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

like image 120
dtjmsy Avatar answered Sep 22 '22 17:09

dtjmsy


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!")]
like image 20
Joe the Coder Avatar answered Sep 24 '22 17:09

Joe the Coder