MVC 後設資料驗證

白馬酒涼發表於2013-09-25

ASP.NET MVC 3 Validation - 正規表示式驗證RegularExpressionAttribute之日期驗證
http://blog.csdn.net/jackvs/article/details/6701186

C#中Dictionary的用法
http://jingyan.baidu.com/article/9989c7460ab872f648ecfeed.html

String.Format格式說明
http://www.cnblogs.com/tuyile006/archive/2006/07/13/449884.aspx

 
《Pro ASP.NET MVC 3 Framework》學習筆記之三十一 【模型驗證】
http://www.cnblogs.com/mszhangxuefei/archive/2012/05/28/mvcnotes_31.html

HTML5 Form Validation Examples
http://www.the-art-of-web.com/html/html5-form-validation/


jQuery Validation Plugin
http://www.the-art-of-web.com/html/html5-form-validation/

 

1.ModelState.IsValid用來判斷model是否通過驗證,前臺顯示如下
@Html.ValidationSummary()
@Html.ValidationMessageFor(model => model.TestName)

2.ModelState 是個Dictionary型別

ModelState.AddModelError("testName","* Test Name is not valid.");
ModelState["TestName"].Errors.Count()

3.DateTime
[DataType(DataType.DateTime,ErrorMessage="Please input date value")]  //  ErrorMessage is not valid
 public DateTime TestTime { get; set; }

DataType後邊的Error Message不起作用,不能覆蓋生成元素的data-val-date/data-val-number屬性,可能對於特殊字串email,url型別的比較有用

[Required(ErrorMessage = "Please input a date value")]  也無效

[RegularExpression(@"^(?:(?!0000)[0-9]{4}(-|\/)(?:(?:0[1-9]|1[0-2])(-|\/)(?:0[1-9]|1[0-9]|2[0-8])|(?:0[13-9]|1[0-2])(-|\/)(?:29|30)|(?:0[13578]|1[02])-31)|(?:[0-9]{2}(?:0[48]|[2468][048]|[13579][26])|(?:0[48]|[2468][048]|[13579][26])00)-02-29)(\s+([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9])?$", ErrorMessage = "Please input a date(YYYY/MM/DD) value")]  有效

但這樣比較累贅,還有個簡單替換生成元素屬性的方法,將-替換成_就可以代替自動生成的資訊了
@Html.TextBoxFor(m => m.Test, new { @data_val_date="please input a valid date"})
這樣我們可以直接新增下列屬性來實現客戶端的認證
data_val_number,data_val_date
data_val_email  無效
data_val_required
data-val-regex-pattern,data-val-regex
data-val-length-min,data-val-length-max,data-val-length
data-val-range-min,data-val-range-max,data-val-range
data-val-remote-url,data-val-remote-type,data-val-remote-additionalfields,data-val-remote   無效

有的時候很奇怪,只對@Html.EditorFor(m => m.Test)有效,卻對@Html.TextBoxFor(m => m.Test)無效,屬性不能正確生成

[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
這種寫法只對@Html.DisplayFor(mbox=>mbox.Test)和@Html.EditorFor(mbox=>mbox.Test)才有效,
對於@Html.LabelFor(mbox=>mbox.Test)和@Html.TextBoxFor(mbox=>mbox.Test)無效

4.String
[Display(Name = "Test Name")]
[Required(ErrorMessage = "Please input the test name.")]
[StringLength(10,ErrorMessage="The length can't longer than 10")]
[StringLength(10, MinimumLength=3)]
[RegularExpression(@"([a-g])*", ErrorMessage = "Please input valid character")]
public string TestName { get; set; }

<input name="Test Name" class="text-box single-line" id="Test" type="text" data-val="true" data-val-regex-pattern="([a-g])*" data-val-regex="valid character" data-val-length-min="3" data-val-length-max="10" data-val-length="length should be 3~10" value=""/>

[DataType(DataType.Password)]
public string Test { get; set; }
<input name="Test" class="text-box single-line valid" id="Test" type="password" value=""/>

5.Number
[Range(1, 100, ErrorMessage = "Please input 1~100.")]
public int Test { get; set; }

<input name="Test" class="text-box single-line" id="Test" type="number" data-val-required="Test is required" data-val="true" data-val-number="Test is not a valid number" data-val-range-min="1" data-val-range-max="100" data-val-range="input 1~100" value="0"/>

6.Enum Type
public enum eReorderLvl
        {
            five = 5,
            ten = 10
        }
[EnumDataType(typeof(eReorderLvl), ErrorMessage = "Please input 5,10")]
        public int Test { get; set; }


 7.Bool
[Range(typeof(bool), "true", "true", ErrorMessage="你必須接受條款")]
public bool TermsAccepted { get; set; }

 
<input name="Test" class="check-box" id="Test" type="checkbox" data-val-required="Test is required" data-val="true" data-val-range-min="True" data-val-range-max="True" data-val-range="must true" value="true"/>

8.以上是屬於System.ComponentModel.DataAnnotations,也可以實時驗證,使用System.Web.Mvc.RemoteAttribute

[Remote("CheckIfExist", "TestName", HttpMethod = "POST", AdditionalFields = "TestId", ErrorMessage = "Test Name already exists.")]
 public string TestName { get; set; }

<input name="TestName" class="required" id="TestName" type="text" data-val="true" data-val-remote-url="/Test/CheckIfExist" data-val-remote-type="POST" data-val-remote-additionalfields="*.TestName,*.TestId" data-val-remote="Test Name already exists" data-fieldname="TestName" value="aaa"/>

9.如果想為基本的型別也在客戶端實時驗證,可以使用
jquery.unobtrusive-ajax.js
jquery.validate.js
Jquery.validate.unobtrusive.js

    <appSettings>
        ...
        <add key="ClientValidationEnabled" value="true" />
        <add key="UnobtrusiveJavaScriptEnabled" value="true" />
    </appSettings>

相關文章