ASP.NET MVC如何實現自定義驗證(服務端驗證+客戶端驗證)
ASP.NET MVC通過Model驗證幫助我們很容易的實現對數據的驗證,在默認的情況下,基於ValidationAttribute的聲明是驗證被使用,我們隻需要將相應的ValidationAttribute應用到Model的類型或者屬性上即可。對於自定義驗證,我們也隻需要定義相應的Validation就可以了,不過服務端驗證比較簡單,而客戶端驗證就要稍微複雜一些,本文提供一個簡單的實例說明在ASP.NET MVC中實現自定義驗證的基本步驟。[源代碼從這裏下載]
用於驗證出生日期字段以確保年齡在製定的範圍之內的AgeRangeAttribute定義如下,簡單起見,我們直接讓它直接繼承自RangeAttribute。服務端驗證邏輯定義在重寫的IsValid方法中,並且重寫了FormatErrorMessage方法以便生成針對年齡的驗證消息。AgeRangeAttribute實現了IClientValidatable接口,並在實現的GetClientValidationRules方法中生成客戶端驗證規則。在生成的類型為“agerange”的ModelClientValidationRule 對象中包含三個參數(currentdate、minage和maxage),分別表示當前日期(用於計算年齡)、允許年齡的範圍。
1: public class AgeRangeAttribute : RangeAttribute, IClientValidatable
2: {
3: public AgeRangeAttribute(int minimum, int maximum)
4: : base(minimum, maximum)
5: { }
6:
7: public override bool IsValid(object value)
8: {
9: DateTime birthDate = (DateTime)value;
10: DateTime age = new DateTime(DateTime.Now.Ticks - birthDate.Ticks);
11: return age.Year >= (int)this.Minimum && age.Year <= (int)this.Maximum;
12: }
13:
14: public override string FormatErrorMessage(string name)
15: {
16: return base.FormatErrorMessage("年齡");
17: }
18:
19: public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
20: {
21: ModelClientValidationRule validationRule = new ModelClientValidationRule(){ ValidationType = "agerange", ErrorMessage= FormatErrorMessage(metadata.DisplayName)};
22: validationRule.ValidationParameters.Add("currentdate",DateTime.Today.ToString("dd-MM-yyyy"));
23: validationRule.ValidationParameters.Add("minage",this.Minimum);
24: validationRule.ValidationParameters.Add("maxage",this.Maximum);
25: yield return validationRule;
26: }
27: }
由於ASP.NET MVC采用JQuery Validation進行客戶端驗證,我們可以通過如下的這段javascript來注冊用於實現客戶端驗證的function和添加相應的adapter。添加到jQuery.validator的用於進行年齡範圍驗證的function具有三個參數(value、element、params)分別表示被驗證的值、元素和傳入的參數。驗證邏輯必須的三個數值(當前日期、年齡範圍最小和最大值)通過參數params獲得。而該參數實際上是在添加adapter時從通過上麵定義的GetClientValidationRules方法生成的驗證規則中獲取的。
1: jQuery.validator.addMethod("agerange",
2: function (value, element, params) {
3:
4: var minAge = params.minage;
5: var maxAge = params.maxage;
6:
7: var literalCurrentDate = params.currentdate;
8: var literalBirthDate = value;
9: var literalCurrentDates = literalCurrentDate.split('-');
10: var literalBirthDates = literalBirthDate.split('-');
11:
12: var birthDate = new Date(literalBirthDates[2], literalBirthDates[1], literalBirthDates[0]);
13: var currentDate = new Date(literalCurrentDates[2], literalCurrentDates[1], literalCurrentDates[0]);
14: var age = currentDate.getFullYear() - birthDate.getFullYear();
15: return age >= minAge && age <= maxAge
16: });
17:
18: jQuery.validator.unobtrusive.adapters.add("agerange", ["currentdate", "minage", "maxage"], function (options) {
19: options.rules["agerange"] = {
20: currentdate: options.params.currentdate,
21: minage: options.params.minage,
22: maxage: options.params.maxage
23: };
24: options.messages["agerange"] = options.message;
25: });
現在我們將AgeRangeAttribute 應用到一個簡單的ASP.NET MVC應用中。在通過VS的ASP.NET MVC項目模板創建的空Web應用中,我們定義了如下一個簡單的Person類型,我們定義的AgeRangeAttribute 應用到了表示出生日期的BirthDate上,並將允許的年齡上、下限設置為18和30。
1: public class Person
2: {
3: [DisplayName("姓名")]
4: public string Name { get; set; }
5:
6: [AgeRange(18, 30, ErrorMessage = "{0}必須在{1}和{2}之間!")]
7: [DisplayName("出生日期")]
8: [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd-MM-yyyy}")]
9: public DateTime? BirthDate { get; set; }
10: }
然後我們添加如下一個HomeController,在默認的Action方法Index中我們將創建的Person對象呈現在默認的View中。
1: public class HomeController : Controller
2: {
3: public ActionResult Index()
4: {
5: return View(new Person{ BirthDate = DateTime.Today, Name = "Foo"});
6: }
7: [HttpPost]
8: public ActionResult Index(Person person)
9: {
10: return View(person);
11: }
12: }
如下所示的代碼片斷代表了View的定義,我們直接調用HtmlHelper<TModel>的擴展方法EditorModel將作為Model的Person對象以編輯模式呈現在一個表單中。最後一點不要忘了在Layout文件中講包含上述javascript片斷的js文件包含進來。
1: @model Person
2: @using (Html.BeginForm())
3: {
4: @Html.EditorForModel()
5: <input type="submit" value="Save" />
6: }
運行我們的程序,輸入不合法出生日期並點擊”Save”按鈕提交表單(針對第一次客戶端驗證),客戶端驗證將會生效,具體效果如下圖所示。
微信公眾賬號:大內老A
微博:www.weibo.com/artech
如果你想及時得到個人撰寫文章以及著作的消息推送,或者想看看個人推薦的技術資料,可以掃描左邊二維碼(或者長按識別二維碼)關注個人公眾號(原來公眾帳號蔣金楠的自媒體將會停用)。
本文版權歸作者和博客園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁麵明顯位置給出原文連接,否則保留追究法律責任的權利。
最後更新:2017-10-26 11:34:22