Link to home
Start Free TrialLog in
Avatar of saturation
saturation

asked on

ASP.NET CustomValidator on checkbox

I'm trying to validate a checkbox with the CustomValidator, but it doesn't seem to be firing.  Does it have to do with the fact that I have some regular validator tags on other fields that are firing when the submit button is clicked?   They all work just fine--but this one doesn't.  There's no message, and no error message, either.  

.ASPX PAGE
<asp:CheckBox ID="chkConsent" runat="server" />
<asp:CustomValidator id="cust_CheckBoxPrint" runat="server" ErrorMessage="Required!" OnServerValidate="ValidateCheckbox">* required</asp:CustomValidator>

CODEBEHIND PAGE
    Sub ValidateCheckbox(ByVal source As Object, ByVal args As ServerValidateEventArgs)
        args.IsValid = (chkConsent.Checked = True)
    End Sub
Avatar of Stephan
Stephan
Flag of Netherlands image

Are you having other validation controls on the page and are they validating on the client-side?

If so, you could add a piece of javascript in order to validate the checkbox on client-side.
Hi,

Try with the following. I had a try with ur code in c# and it worked.

Sub ValidateCheckbox(ByVal source As Object, ByVal args As ServerValidateEventArgs)
        If chkConsent.Checked = True Then
              args.IsValid = True
        Else
              args.IsValid = False
       End IF
    End Sub

<form id="form1" runat="server">
   
    <asp:CheckBox ID="chkConsent" runat="server" />
    <asp:CustomValidator ID="cust_CheckBoxPrint" runat="server" ErrorMessage="Required!"
        OnServerValidate="ValidateCheckbox">* required</asp:CustomValidator>
    <asp:Button ID="Button1" Text="Submit" runat="server"/>
    </form>
Also the ControlToValidate property is also missing...
Avatar of saturation
saturation

ASKER

So, I've noticed one more thing...The checkbox unchecked does prevent the page from being submitted, but there is no message that comes up if it's not checked.   Any ideas?
ASKER CERTIFIED SOLUTION
Avatar of Stephan
Stephan
Flag of Netherlands image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Make sure when you disable client validation that you need to add if(Page.IsValid) { //validated }
On your event where you want to process the posted data
write code in form submit event (saving data to DB).
 if (!cust_CheckBoxPrint.IsValid)
                    {
                       
                    }
Does it show the error message if you use

<asp:CheckBox ID="chkConsent" runat="server" />
<asp:CustomValidator id="cust_CheckBoxPrint" runat="server" ErrorMessage="Required!" OnServerValidate="ValidateCheckbox" Text="* required" ErrorMessage="* Required" />

?