標籤:
其實是很少發技術類文章的, 只是在最近的一次項目中,由於這個位置的技術短板導致折騰好幾天,而網上搜的內容又都不直接說明,所以還是決定寫出來給人蔘考一下, 可以協助大家省點時間。
先來看一下需求:
很是草稿的圖片請別介意。需求是這樣,當選中圖中的下拉式功能表選項為第一個時,使用文字驗證,當下拉式功能表選為第二個選項時,使用數字驗證。這種需求其實比較普遍,很多流程化管理的頁面都會有這種需求。比如在申請證件時候可選項是護照還是身份證的時候,對填入內容的驗證規則可以是不一樣的。 但微軟內建的model綁定規則是只能適用一種規則,因此我們需要自己重寫驗證規則來滿足我們的需求。因此,我們寫下的代碼可能會是這樣的:
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
這隻是實現了其中一種“必填”的策略罷了
所以我們要解決我們面臨的問題的第一步是需要做一個定製化的屬性標籤。
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true, Inherited = true)] public class CustomdropdownlistAttribute : ValidationAttribute, IClientValidatable { private const string _defaultErrorMessage = "‘{0}‘ must be at least {1} characters long."; private readonly int _minCharacters = Membership.Provider.MinRequiredPasswordLength; public CustomdropdownlistAttribute() : base(_defaultErrorMessage) { } public override string FormatErrorMessage(string name) { return String.Format(CultureInfo.CurrentCulture, ErrorMessageString, name, _minCharacters); } protected override ValidationResult IsValid(object value, ValidationContext validationContext) { string valueAsString = value as string; var containerType = validationContext.ObjectInstance.GetType(); var field = containerType.GetProperty("MydSelect"); return (int)field.GetValue(validationContext.ObjectInstance, null) == 0 ? ValidationResult.Success : new ValidationResult(this.ErrorMessage, new[] { validationContext.MemberName }); } //機理是通過validationContext擷取當前model的所有屬性,通過反射擷取要驗證的欄位的值,“MydSelect”是下拉式功能表的欄位名稱 public IEnumerable GetClientValidationRules(ModelMetadata metadata, ControllerContext context) { return new[]{ new ModelClientValidationRule{ ValidationType="validatedropdownlist", ErrorMessage="must be int"//FormatErrorMessage(metadata.DisplayName)//this.ErrorMessage } }; } } Customdropdownlist標籤實現後就可以用來裝飾我們需要驗證的model對象裡的欄位。
[Customdropdownlist] [Required] [Display(Name = "User name")] public string UserName { get; set; }
這個個人化實現的標籤可以直接扔在viewmodel類裡,因為每個model的內的驗證規則或許會有細微差別, 隨著業務發展,也會出現更多頁面出現類似的需求。屆時我們可以把它們抽出成一個統一的類。
此時,其實完成了服務端的驗證過程,你需要做的就是根據你的需要來實現 ValidationResult IsValid(object value, ValidationContext validationContext)這個函數。不過要記住要把這個函數的實現用overide 和protected,不然後面報一個很奇怪的錯,表示有一個bool IsValid(object value)的函數沒有被重寫的錯誤。 原因是雖然都是IsValid,但是之間存在相互調用的關係。 因此如果被聲明成public,就會報錯。 以上都是model.cs檔案中關於model的服務端驗證代碼。 要想真正實現用戶端驗證,還需要在你的.cshtml檔案中註冊相應的JS指令碼。 jQuery.validator.unobtrusive.adapters.add("validatedropdownlist", function (options) { options.rules["validatedropdownlist"] = true; if (options.message) { options.messages["validatedropdownlist"] = options.message; } }); jQuery.validator.addMethod("validatedropdownlist", function (value) { if (($(‘#dropdownlist‘).val() == 0)) return true }); 網上有人說validator適配器上方法名validatedropdownlist一定要全小寫, 我沒試過,但至少全小寫是可以work.於是不想浪費時間地全部小寫了。 其中$((‘#dropdownlist‘))是dropdownlist在運行後頁面中下拉框的名字, 我們其實可以把這個名字作為參數傳到頁面中,這裡只是偷了個懶,請不要在意這些細節 。最後,不要忘了在web.config中開啟用戶端驗證
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
這裡還有篇外國人寫的很不錯的過程, 可以用來參考和擴充功能。 http://anthonyvscode.com/2011/07/14/mvc-3-requiredif-validator-for-multiple-values/
如何在.net/MVC4中自訂頁面驗證的前端指令碼