MVC3: set the checkbox required with jQuery validation?

I want my “Agree to terms” checkbox to be mandatory using jQuery validation in an MVC3 project. I am currently receiving DRY / SPOT server / client authentication from "MS data annotation attributes" + "MS MVC3 unobtrusive jQuery verification".

Here's a separate test (plain HTML created by MVC3). Why is this not working please? At startup, checking that the Contact Name field is correctly filled in, but does not matter for the state of the flag.

<!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> 





The rest of this post is just my research notes.

The value of the data annotation attribute [required] does not help:
http://forums.89.biz/forums/MVC+3+Unobtrusive+validation+does+not+work+with+checkboxes+(jquery+validation)+and+the+fix+for+it .

It's good. What “required” means for a flag is obviously a holy war that I don’t want to go into, where MS thought they knew better than the jquery team. Forcing local use should be simple: $("form").validate({ rules: { cbAgreeToTerms: "required" } });

... is not it? no, due to:
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

What? This is a pretty smelly cheezy! (IMHO, of course.)

Now I tried this solution:
http://itmeze.com/2010/12/checkbox-has-to-be-checked-with-unobtrusive-jquery-validation-and-asp-net-mvc-3/
and it did not work for me. This author, chatting in the comments and somewhat rudely used inverted CHECKBOX test from earlier in her article, makes me wonder if this really works for him / her, and then what other voodoo was involved?

Note. I think the last JS snippet is equivalent to clearing:
$.validator.unobtrusive.adapters.addBool("brequired", "required"); This was suggested in a last post at:
http://forums.asp.net/p/1648319/4281140.aspx#4281140
But note that the author comments that he has not debugged it yet. This did not work for me and, reading between the lines, I think it means that it did not work for him?

Unobtrusive.js calls the parsing on docready, so I tried calling, but that didn't help me.
$.validator.unobtrusive.parse(document); I also found several similar articles, and no one talks about the need for initialization. Maybe they all locally edit the original / public unobtrusive.js? I would prefer that I can help, why do I need adapters?

I found articles almost the same, as well as more complex examples:
ASP.NET MVC 3 unobtrusive user validation validation
Perform client side validation for custom attribute
http://xhalent.wordpress.com/2011/01/27/custom-unobstrusive-jquery-validation-in-asp-net-mvc-3/
But I don’t see anything there, which is different from what I have already tried.

Does it really work for people? Why can't I make it work for me?

+44
jquery jquery-validate asp.net-mvc
Feb 08 '11 at 2:07 a.m.
source share
3 answers

Just change your javascript to this:

 (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)); 

In fact, you do not need to write your own adapter, and it can just use:

 (function ($) { $.validator.unobtrusive.adapters.addBool("mandatory", "required"); } (jQuery)); 
+32
Feb 08 '11 at 16:40
source share

I have given here the correct source code obtained as a result of applying the accepted answer. I hope you find this helpful.

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; } } 
+59
Mar 22 '11 at 0:40
source share
 <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> 
0
Feb 18 '11 at 12:16
source share



All Articles