如何在 ASP.NET MVC 2 RC 中編寫自定義客戶端 jQuery 驗證?
我已經閱讀了Phil Haack 的關於 ASP.NET MVC 2 中的自定義客戶端驗證的文章。我想做同樣的事情,但是使用 jQuery 適配器並使用 ASP.NET MVC 2 RC(而不是文章的 MVC 2 Beta用途)。有沒有人能夠弄清楚如何做到這一點?
我特別想實現密碼匹配驗證(即密碼和確認密碼必須匹配)。ASP.NET MVC 2 RC VS.NET 項目模板確實展示瞭如何在伺服器端(使用
PropertiesMustMatchAttribute)而不是在客戶端實現它。
我假設您已經按照 Phil Haack 的說明(http://haacked.com/archive/2009/11/19/aspnetmvc2-custom-validation.aspx)了解如何使用 MS AJAX 客戶端驗證進行自定義驗證。要讓它與 jQuery 一起工作,您需要修改 MicrosoftMvcJQueryValidation.js 文件:
- 在 __MVC_CreateRulesForField(validationField) 函式中,您需要添加一個 case 語句。繼續 Phil 的範例,您需要添加:
案例“價格”:
__MVC_ApplyValidator_Price(rulesObj, thisRule.ValidationParameters
$$ “min” $$); 休息;
- 然後,您需要創建 __MVC_ApplyValidator_Price 函式:
函式__MVC_ApplyValidator_Price(對象,值){
// min is what jQuery Validate uses to validate for minimum values object["min"] = value;}
這應該足以讓 Phil 的範例正常工作。
現在,關於您的 PropertiesMustMatchAttribute 驗證,看起來 MVC 不會為裝飾類的屬性生成客戶端 json 驗證定義。由於必須在模型(而不是屬性)上使用 PropertiesMustMatchAttribute,我無法弄清楚如何讓它觸發客戶端驗證。相反,我採取了不同的方法。我創建了一個虛擬驗證屬性,其 IsValid() 重載始終返回 true,並在屬性上使用了此屬性。這只是一個虛擬屬性,它將驗證邏輯委託給 jQuery 驗證器的 equalTo 函式。這是虛擬屬性:
public class PropertiesMustMatchClientTriggerAttribute : ValidationAttribute { public string MatchProperty { get; set; } public PropertiesMustMatchClientTriggerAttribute(string matchProperty) { MatchProperty = matchProperty; ErrorMessage = "{0} doesn't match {1}."; } public override bool IsValid(object value) { return true; } public override string FormatErrorMessage(string name) { return String.Format(CultureInfo.CurrentCulture, ErrorMessageString, name, MatchProperty); } }這是自定義驗證器:
public class PropertiesMustMatchClientTriggerValidator : DataAnnotationsModelValidator<PropertiesMustMatchClientTriggerAttribute> { private string _message; private string _matchProperty; public PropertiesMustMatchClientTriggerValidator(ModelMetadata metaData, ControllerContext context, PropertiesMustMatchClientTriggerAttribute attribute) : base(metaData, context, attribute) { _message = attribute.FormatErrorMessage(metaData.DisplayName); _matchProperty = attribute.MatchProperty; } public override IEnumerable<ModelClientValidationRule> GetClientValidationRules() { var rule = new ModelClientValidationRule { ErrorMessage = _message, ValidationType = "equalTo" }; rule.ValidationParameters.Add("matchField", _matchProperty); return new[] { rule }; } }根據 Phil 的部落格,上述自定義驗證器需要在 Application_Start() 中註冊:
DataAnnotationsModelValidatorProvider.RegisterAdapter (typeof (PropertiesMustMatchClientTriggerAttribute), typeof (PropertiesMustMatchClientTriggerValidator));
最後,需要修改 MicrosoftMvcJQueryValidation.js 文件:
- 將以下 case 語句添加到 __MVC_CreateRulesForField:
案例“等於”:
__MVC_ApplyValidator_EqualTo(rulesObj, thisRule.ValidationParameters
$$ “matchField” $$); 休息;
- 添加此功能:
函式 __MVC_ApplyValidator_EqualTo(object, elemId) {
object["equalTo"] = document.getElementById(elemId);}
現在您需要將虛擬驗證屬性附加到屬性:
[PropertiesMustMatchClientTrigger("Password")] public string ConfirmPassword { get; set; }那應該這樣做。
創建這個虛擬屬性有點難看,所以我希望有人能想出一個更優雅的解決方案。