从这个博客http://bradwilson.typepad.com/blog/2010/10/mvc3-unobtrusive-validation.html
Bridging HTML and jQuery Validate: Adapters
Writing a client-side validator involves two steps: writing the
validator for jQuery Validate,and writing the adapter which takes the
parameter values from the HTML attributes and turns it into jQuery
Validate Metadata. The former topic is not in the scope of this blog
post (since it’s really not MVC specific).There is an adapter collection available at
jQuery.validator.unobtrusive.adapters. Hanging off the adapter
collection is the adapter registration method (add) and three helpers
that can be used to register very common types of adapters (addBool,
addSingleVal,and addMinMax).
请注意,它说了两步.
但是,如果你看这个帖子MVC3: make checkbox required via jQuery validate?,你只需要第二步(“写适配器”)来进行验证工作 – 添加以下代码行:
$.validator.unobtrusive.adapters.addBool("mandatory","@R_502_103@");
我在一个新的MVC 4互联网应用程序中测试了代码,它的工作正常,这里是超简单的示例.
查看模型
public class Simpleviewmodel { [Mandatory(ErrorMessage = "You must agree to the Terms to register.")] [Display(Name = "Terms Accepted")] public bool IsTermsAccepted { get; set; } }
验证属性
public class MandatoryAttribute : ValidationAttribute,IClientValidatable { public override bool IsValid(object value) { return (!(value is bool) || (bool)value); } public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata Metadata,ControllerContext context) { ModelClientValidationRule rule = new ModelClientValidationRule(); rule.ErrorMessage = FormatErrorMessage(Metadata.GetDisplayName()); rule.ValidationType = "mandatory"; yield return rule; } }
视图
@model MvcApplication2.Models.Simpleviewmodel @{ ViewBag.Title = ""; } @using (Html.BeginForm()) { @Html.ValidationSummary() @Html.CheckBoxFor(model => model.IsTermsAccepted) @Html.ValidationMessageFor(model => model.IsTermsAccepted) <input type="submit" value="Send" /> } @section Scripts { @Scripts.Render("~/bundles/jqueryval") <script type="text/javascript"> $.validator.unobtrusive.adapters.addBool("mandatory","@R_502_103@"); </script> }
所以基本上我有三个问题:
>是$.validator.unobtrusive.adapters.addBool(“mandatory”,“@R_502_103@”);除了写一个属性类,你真的需要你唯一需要的东西吗?
>幕后做了什么?
>在哪里可以找到关于addBool的很好的文档?
解决方法
>是的,这是属性之外唯一需要的.那是因为我们使用已经存在的规则(必需).
>它做什么?
This just registers a new validation adapter for the MandatoryAttribute,
where the first parameter is the adapter name and the
second parameter is the name of jQuery validate rule. The adapter name
should match the value we specified earlier as the validation type,
and the jQuery validation @R_502_103@-rule will require the user to check
the checkBox.
3.更多信息,请参见this article on Brad Wilson’s blog.