asp.net-mvc – 如何在ASP.NET MVC 2 RC中编写自定义客户端jQuer
我已经在ASP.NET MVC 2中的自定义客户端验证上阅读了
Phil Haack’s post.我想做同样的事情,但使用jQuery适配器和使用ASP.NET MVC 2 RC(而不是MVC 2测试版,该帖子使用) .有没有人能够看出如何做到这一点?
我特意要实现密码匹配验证(即密码和确认密码必须匹配). 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(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; } 应该这样做 创建这个虚拟属性有点丑陋,所以我希望有人可以提出一个更优雅的解决方案. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |