Problem:
I want to validate some ASP.NET-checkboxes using the jquery validation plugin (found at: http://bassistance.de/jquery-plugins/jquery-plugin-validation/)
What it's all about:
It's not possible to set the name attribute of ASP.NET checkboxes (or is it?). It'll automatically be set, when the control is rendered and can be retrieved using
<%= emailCheckBox.UniqueID %>
So two checkboxes as the following:
<asp:CheckBox runat="server" ID="emailAcceptCheckBox" />Email<br />
<asp:CheckBox runat="server" ID="phoneAcceptCheckBox" />Phone<br />
will render to:
<INPUT id="ctl00_MainContentPlaceHolder_emailAcceptCheckBox" type="checkbox" name="ctl00$MainContentPlaceHolder$emailAcceptCheckBox">
<INPUT id="ctl00_MainContentPlaceHolder_phoneAcceptCheckBox" type="checkbox" name="ctl00$MainContentPlaceHolder$phoneAcceptCheckBox">
Maybe it's a mess to mix ASP.NET with the jquery validation plugin, but I prefer the jquery validation plugin and it works fine with inputs and other fields.
Problem is, that the jquery validation plugin wants to group the checkboxes using the name-attribute of checkboxes. This name attributes should be equal to all checkboxes and a group.
What I've done:
I added a rule to ALL checkboxes using jquery:
$("#[id*='AcceptCheckBox']").each(function() { $(this).rules("add", { minchecked: 1 }); });
And added my own rule checking for checkboxes:
jQuery.validator.addMethod("minchecked",
function(value, element, param) {
var noOfChecked = $("#[id*='AcceptCheckBox']:checked").length;
return noOfChecked >= param;
},
"Error");
(This rule will apply for checkboxes whose IDs include AcceptCheckBox, but it's okay in this example).
When I call:
var result = $("#aspnetForm").validate().form();
It returns perfectly if my validation succeeded or failed!
BUT:
1) I don't feel that this is a very clean and nice solution. Any better advice?
2) When I run validate().form() it'll go through ALL my checkboxes and for each of them check all the other checkboxes. That's really not necessary. How can I avoid this?