MVC3 jquery验证MinLength过滤器无法正常工作

Rog*_*Far 16 asp.net-mvc jquery-validate asp.net-mvc-3

我在我的模式中有这个:

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

最终结果如下:

    <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>
Run Code Online (Sandbox Code Playgroud)

为什么MinLength会被编译器忽略?我怎么能"开启"?

dtj*_*msy 32

而不是使用MinLength属性使用此代替:

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

字符串长度MSDN

优点:无需编写自定义属性


Joe*_*der 9

而不是经历创建自定义属性的麻烦...为什么不使用正则表达式?

// 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!")]
Run Code Online (Sandbox Code Playgroud)


Jos*_*uch 6

最新版本的ASP.Net MVC现在支持MinLength和MaxLength属性.查看官方asp.net mvc页面:MinLengthAttribute和MaxLengthAttribute的不显眼验证