程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> ASP.NET >> 關於ASP.NET >> ASP.NET MVC如何實現自定義驗證(服務端驗證+客戶端驗證)

ASP.NET MVC如何實現自定義驗證(服務端驗證+客戶端驗證)

編輯:關於ASP.NET

ASP.NET MVC通過Model驗證幫助我們很容易的實現對數據的驗證,在默認的情況下,基於ValidationAttribute的聲明是驗證被使用,我們只需要將相應的ValidationAttribute應用到Model的類型或者屬性上即可。對於自定義驗證,我們也只需要定義相應的Validation就可以了,不過服務端驗證比較簡單,而客戶端驗證就要稍微復雜一些,本文提供一個簡單的實例說明在ASP.NET MVC中實現自定義驗證的基本步驟。[源代碼從這裡下載]

一、AgeRangeAttribute

用於驗證出生日期字段以確保年齡在制定的范圍之內的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: });

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved