In this article I will explain with an example, how to validate CheckBox control using CustomValidator and
JavaScript in ASP.Net.
HTML Markup
The HTML Markup consists of following controls:
CheckBox – For capturing user input.
Button – For submitting the Form.
CustomValidator – To ensure the CheckBox is checked before PostBack.
The CustomValidator has been set with the following event handler:
ClientValidationFunction – For setting the
ValidateCheckBox JavaScript function.
<asp:CheckBox ID="CheckBox1" runat="server" />
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Required" ClientValidationFunction="ValidateCheckBox"></asp:CustomValidator>
<br /><br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" />
Validating CheckBox using JavaScript
When the
Submit Button is clicked, the
ValidateCheckBox JavaScript function gets called.
Inside the
ValidateCheckBox JavaScript function, a check is performed whether the CheckBox is checked or not.
If checked then it returns TRUE else FALSE.
<script type="text/javascript">
function ValidateCheckBox(sender, args) {
args.IsValid = document.getElementById("<%=CheckBox1.ClientID%>").checked ? true : false;
}
</script>
Screenshot
Browser Compatibility
* All browser logos displayed above are property of their respective owners.
Demo
Downloads