Required Field Validator for Checkbox in ASP.NET

Unlike other form fields, ASP.NET does not have a required field validator control for checkbox. You have to roll your own with a custom field validator. Quick and easy example straight from Microsoft:

Checkbox Control

<asp:Label Font-Bold="true" 
  ID="lbl_CheckBoxPrint" 
  Text="I have the ability to print from this computer or device:"   
  AssociatedControlID="CheckBoxPrint" runat="server" />

<asp:CheckBox  
  id="CheckBoxPrint" 
  runat="server"></asp:CheckBox>

Custom Validator

<asp:CustomValidator 
  id="cust_CheckBoxPrint" 
  runat="server" 
  ErrorMessage="Print Capability" 
  OnServerValidate="ValidatePrint">* required</asp:CustomValidator>

Do not forget to put the validation function name in the OnServerValidate attribute.

Validation Code

Sub ValidatePrint(ByVal source As Object, ByVal args As ServerValidateEventArgs)
        args.IsValid = (CheckBoxPrint.Checked = True)
End Sub

Not that hard, but not quite as easy as just adding a required field validator control.

Complete Code

  <asp:Label Font-Bold="true" 
    ID="lbl_CheckBoxPrint" 
    Text="I have the ability to print from this computer or device:"    
    AssociatedControlID="CheckBoxPrint"
    runat="server" />

<asp:CheckBox 
  id="CheckBoxPrint" 
  runat="server"></asp:CheckBox>

<asp:CustomValidator 
   id="cust_CheckBoxPrint" 
   runat="server"
   ErrorMessage="Print Capability" 
   OnServerValidate="ValidatePrint">* required</asp:CustomValidator>

'This goes in a script block or on a code behind page
Sub ValidatePrint(ByVal source As Object, ByVal args As ServerValidateEventArgs)
        args.IsValid = (CheckBoxPrint.Checked = True)
End Sub
Posted in .net, Web development. Tags: , . Permalink. Both comments and trackbacks are closed.