我特意要实现密码匹配验证(即密码和确认密码必须匹配). ASP.NET MVC 2 RC VS.NET项目模板显示了如何在服务器端实现(使用PropertiesMustMatchAttribute),但不在客户端.
解决方法
>在__MVC_CreateRulesForField(validationField)函数中,您需要添加一个case语句.继续Phil的例子,你需要添加:
案例“价格”:
__MVC_ApplyValidator_Price(rulesObj,thisRule.ValidationParameters [“min”]);
打破;
>然后,您需要创建__MVC_ApplyValidator_Price函数:
函数__MVC_ApplyValidator_Price(object,value){
// min is what jQuery Validate uses to validate for minimum values object["min"] = value;
}
这应该足以让菲尔的榜样工作.
现在,关于PropertiesMustMatchAttribute验证,它不像MVC生成用于装饰类的属性的客户端json验证定义.由于必须在模型上使用PropertiesMustMatchAttribute(而不是属性),所以我无法弄清楚如何触发客户端验证.相反,我采取了不同的做法.我创建了一个虚拟验证属性,IsValid()重载总是返回true,并在属性上使用此属性.这只是一个虚拟属性,将验证逻辑委托给jQuery验证器的equalsTo函数.这是虚拟属性:
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:
case“equalTo”:
__MVC_ApplyValidator_EqualTo(rulesObj,thisRule.ValidationParameters [“matchField”]);
打破;
函数__MVC_ApplyValidator_EqualTo(object,elemId){
object["equalTo"] = document.getElementById(elemId);
}
[PropertiesMustMatchClientTrigger("Password")] public string ConfirmPassword { get; set; }
应该这样做