Asp.net-Mvc

MVC3 jquery驗證MinLength過濾器不起作用

  • September 27, 2016

我的模式中有這個:

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

這最終出現在:

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

編譯器為什麼會忽略 MinLength?我怎樣才能“打開它”?

而不是使用MinLength屬性,而是使用它:

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

字元串長度 MSDN

優點:無需編寫自定義屬性

而不是經歷創建自定義屬性的麻煩……為什麼不使用正則表達式?

// 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!")]

引用自:https://stackoverflow.com/questions/7187773