Thursday, March 22, 2012

ASP.NET : At least one check box must be checked

 

The ASP.NET Validation Controls are a really neat way of doing user validation. However, they are pretty basic. What about more complicated stuff? For that you need a CustomValidator.

e.g. I have a number of check boxes on the page and one of the validation rules is that at least one of the check boxes must be checked. Mr Google to the rescue and (roll of drums) the answer is:

Put this script at the top of the page:

<script runat="server">

void CustomValidator_CBValidate(Object source, ServerValidateEventArgs args)
{
args.IsValid = (chkBox1.Checked == true) || (chkBox2.Checked == true) || ...;
}

</script>



And then in your page:



<asp:CheckBox ID="chkBox1" Text="xxx" runat="server" />

<asp:CheckBox ID="chkBox2" Text="yyy" runat="server" />

...

<asp:CustomValidator id="CustomValidator1"
runat="server" ErrorMessage="Please select an option"
OnServerValidate="CustomValidator_CBValidate">
</asp:CustomValidator>


Enjoy!



No comments: