MVC3:使checkbox需要通过jQueryvalidation?

我希望我的“同意条款”checkbox是强制使用jQueryvalidation,在一个MVC3项目。 我目前从“MS数据注释属性”+“MS MVC3不显眼的jQueryvalidation”服务器/客户端干/ SPOTvalidation。

这是一个独立的testing(由MVC3生成的纯HTML)。 为什么它不工作,请? 运行时,validation可确保填写“联系人姓名”字段,但不关心checkbox的状态。

<!DOCTYPE html> <html> <head> <title>RequiredCheckbox</title> <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script> <script type="text/javascript" src="//ajax.microsoft.com/ajax/jQuery.Validate/1.7/jQuery.Validate.js"></script> <script type="text/javascript" src="//ajax.aspnetcdn.com/ajax/mvc/3.0/jquery.validate.unobtrusive.js"></script> <script type="text/javascript" language="javascript"> $(function () { // http://itmeze.com/2010/12/checkbox-has-to-be-checked-with-unobtrusive-jquery-validation-and-asp-net-mvc-3/ $.validator.unobtrusive.adapters.add("mandatory", function (options) { options.rules["required"] = true; if (options.message) { options.messages["required"] = options.message; } } }); $.validator.unobtrusive.parse(document); }); </script> </head> <body> <div> <form> <input data-val="true" data-val-mandatory="The field Terms Are Accepted is invalid." id="isTermsAccepted" name="isTermsAccepted" type="checkbox" value="true" /> <input name="isTermsAccepted" type="hidden" value="false" /> <span class="field-validation-valid" data-valmsg-for="isTermsAccepted" data-valmsg-replace="true"></span> <input data-val="true" data-val-required="The Contact Name field is required." id="contactName" name="contactName" type="text" value="" /> <span class="field-validation-valid" data-valmsg-for="contactName" data-valmsg-replace="true"></span> <button type="submit">Submit</button> </form> </div> </body> </html> 

这篇文章的其余部分只是我的研究笔记。

设置数据注释属性[必填]没有帮助:
http://forums.89.biz/forums/MVC+3+Unobtrusive+validation+does+not+work+with+checkboxes+(jquery+validation)+and+the+fix+for+it 。

没关系。 什么“需要”意味着一个checkbox显然是一个我不想涉足的圣战,MS认为他们比jquery团队知道的更好。 胁迫本地应该是一个简单的问题:
$("form").validate({ rules: { cbAgreeToTerms: "required" } });

…对? 不,因为:
http://blog.waynebrantley.com/2011/01/mvc3-breaks-any-manual-use-of-jquery.html
http://pinoytech.org/question/4824071/microsofts-jquery-validate-unobtrusive-makes-other-validators-skip-validation

什么? 这真是太臭了! (恕我直言,当然。)

现在,我试过这个解决scheme:
http://itmeze.com/2010/12/checkbox-has-to-be-checked-with-unobtrusive-jquery-validation-and-asp-net-mvc-3/
这对我没有用。 这篇作者悬而未决的评论和早些时候在他/她的文章中使用倒置的CHECKBOXtesting使我怀疑它是否真的对他/她有用,那么还有什么其他的巫术呢?

注意我认为JS的最后一个片段相当于更清洁:
$.validator.unobtrusive.adapters.addBool("brequired", "required"); 这是最后一篇文章中提出的:
http://forums.asp.net/p/1648319/4281140.aspx#4281140
但请注意,作者评论说,他还没有debugging过。 它不适合我,阅读之间的界限,我认为他的意思是没有为他工作?

unobtrusive.js调用parsingdocready,所以我试着调用,但它并没有帮助我。
$.validator.unobtrusive.parse(document); 我也发现了一些类似的文章,没有谈到要求初始化的任何types。 也许他们都在本地编辑原始/公共unobtrusive.js? 我宁愿不能,如果我能帮助它,是不是适配器是什么?

我发现堆栈溢出的文章,以及更复杂的例子:
ASP .Net MVC 3不显眼的自定义客户端validation
执行自定义属性的客户端validation
http://xhalent.wordpress.com/2011/01/27/custom-unobstrusive-jquery-validation-in-asp-net-mvc-3/
但是我看不出有什么不同于我已经尝试过的。

这真的是为人们工作吗? 为什么我不能为我工作?

只需将您的JavaScript更改为:

 (function ($) { // http://itmeze.com/2010/12/checkbox-has-to-be-checked-with-unobtrusive-jquery-validation-and-asp-net-mvc-3/ $.validator.unobtrusive.adapters.add("mandatory", function (options) { options.rules["required"] = true; if (options.message) { options.messages["required"] = options.message; } }); } (jQuery)); 

您实际上并不需要编写自己的适配器,只需使用:

 (function ($) { $.validator.unobtrusive.adapters.addBool("mandatory", "required"); } (jQuery)); 

我在这里总结了正确工作的源代码,这是源于应用接受的答案。 希望你觉得它有用。

RequiredCheckbox.aspx

 <%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<RegistrationViewModel>" %> <!DOCTYPE html> <html> <head runat="server"> <title>RequiredCheckbox</title> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script> <script src="//ajax.microsoft.com/ajax/jQuery.Validate/1.7/jQuery.Validate.js" type="text/javascript"></script> <script src="//ajax.aspnetcdn.com/ajax/mvc/3.0/jquery.validate.unobtrusive.js" type="text/javascript"></script> <script type="text/javascript" language="javascript"> $.validator.unobtrusive.adapters.addBool("mandatory", "required"); </script> </head> <body> <div> <% // These directives can occur in web.config instead Html.EnableUnobtrusiveJavaScript(); Html.EnableClientValidation(); using (Html.BeginForm()) { %> <%: Html.CheckBoxFor(model => model.IsTermsAccepted)%> <%: Html.ValidationMessageFor(model => model.IsTermsAccepted)%> <%: Html.TextBoxFor(model => model.ContactName)%> <%: Html.ValidationMessageFor(model => model.ContactName)%> <button type="submit">Submit</button> <% } %> </div> </body> </html> 

RegistrationViewModel.cs

 using System; using System.ComponentModel; using System.ComponentModel.DataAnnotations; public class RegistrationViewModel { [Mandatory (ErrorMessage="You must agree to the Terms to register.")] [DisplayName("Terms Accepted")] public bool isTermsAccepted { get; set; } [Required] [DisplayName("Contact Name")] public string contactName { get; set; } } 

MandatoryAttribute.cs

 using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Web.Mvc; 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; } } 
 <asp:Content ID="Content1" ContentPlaceHolderID="MainContentPlaceHolder" runat="server"> <h2> Save New Contact</h2> <%using (Html.BeginForm("SaveContact", "Contact", FormMethod.Post, new { id = "UserImportTypeForm", @autocomplete = "off" })) %> <%{ %> <table style="height: 100px;"> <tr> <td> Import Type : </td> </tr> <tr> <td> Is Verified </td> <td> <%-- <%=Html.TextBox("UserContactModel.IsVerified", new SelectList(Model.IsVerified, "IsVerified"), new { })%>>--%> <%-- <input type="text" name="txtIsVerified" id="txtIsVerified" />--%> <%-- <%= Html.TextBox("txtIsVerified")%>--%> <%=Html.CheckBox("SelectedUserContact.IsVerified", Convert.ToBoolean(Model.SelectedUserContact.IsVerified) )%> <%=Html.ValidationSummary("txtIsVerified", "*")%> </td> </tr> <tr> <td> First Name </td> <td> <%--<input type="text" name="txtFirstName" id="txtFirstName" />--%> <%=Html.TextBox ("SelectedUserContact.FirstName", Model.SelectedUserContact.FirstName )%> <%-- <%=Html.ValidationSummary("FirstName", "*")%>--%> </td> </tr> <tr> <td> Last Name </td> <td> <%--<input type="text" name="txtLastName" id="txtLastName" />--%> <%=Html.TextBox("SelectedUserContact.LastName", Model.SelectedUserContact.LastName)%> <%=Html.ValidationSummary("LastName", "*")%> </td> </tr> <tr> <td> Contact ID </td> <td> <%=Html.TextBox("SelectedUserContact.ContactID",Model.SelectedUserContact.ContactID) %> <%=Html.ValidationSummary("ContactID","*") %> </td> </tr> <tr> <td align="right"> <input type="submit" value="Save" name="btnSave" id="btnSave" /> </td> <td> <input type="button" value="Cancel" name="btnCancel" id="btnCancel" /> </td> </tr> </table> <%} %> <script src="../../Scripts/jquery.validate.js" type="text/javascript"></script> <script language="javascript" type="text/javascript"> $("#UserImportTypeForm").validate({ rules: { "SelectedUserContact.FirstName": { required: true }, "SelectedUserContact.LastName": { required: true }, "SelectedUserContact.ContactID": {required:true} }, messages: { "SelectedUserContact.FirstName": { required: "*" }, "SelectedUserContact.LastName": { required: "*" }, "SelectedUserContact.ContactID": { required: "*" }, } }); </script> </asp:Content>