Validating a checkbox

Discussion in 'ASP .Net' started by Scott Natwick, Nov 11, 2004.

  1. I would like to validate that a Checkbox is checked on the client-side.

    I have tried the "requiredfieldvalidator" and the
    "regularexpressionvalidator", but haven't been able to get either of them to
    work the Checkbox.

    Any suggestions?

    Thanks,
    Scott
     
    Scott Natwick, Nov 11, 2004
    #1
    1. Advertisements

  2. Scott,
    If you have tried the RequiredFieldValidator, you would have seen:
    Control 'chk' referenced by the ControlToValidate property of
    'RequiredFieldValidator1' cannot be validated.

    Indeed, the built-in validator controls cannot validate the checkbox. You
    will have to use the custom validator to do this or write your own client
    side validation.

    A quick search of Google for "asp.net validate checkbox", you would find
    that one of the results is:
    http://msdn.microsoft.com/library/d.../html/aspnet-validateaspnetservercontrols.asp,
    and this explains how validations work.

    Here's a page that validates a checkbox:

    <%@ Page language="c#" Codebehind="ValidateCheckbox.aspx.cs"
    AutoEventWireup="false" Inherits="WebApplication1.ValidateCheckbox" %>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
    <HTML>
    <HEAD>
    <script language="javascript">
    function ValidateChecked(oSrc, args){
    if(document.all["<%=chk.ClientID%>"].checked == false){
    alert("Has to be checked.");
    args.IsValid = false;
    }
    }
    </script>
    </HEAD>
    <body>
    <form id="Form1" method="post" runat="server">
    <asp:CustomValidator ClientValidationFunction="ValidateChecked"
    Runat="server" ID="val"/>
    <asp:CheckBox ID="chk" Runat="server" />
    <asp:Button ID="btn" Runat="server" Text="Submit" />
    </form>
    </body>
    </HTML>

    Best regards,
    Jeffrey Palermo
     
    Jeffrey Palermo [MCP], Nov 12, 2004
    #2
    1. Advertisements

  3. Jeffrey,

    Thank you for your suggestion. I used your example and it works!

    Regards,
    Scott

     
    Scott Natwick, Nov 12, 2004
    #3
  4. Scott Natwick

    ZioBelin

    Joined:
    Apr 3, 2012
    Messages:
    1
    Likes Received:
    0
    Thanks

    I've used your example...thanks! You saved me some working hour! :lol:

    Regards,
    ZioBelin

     
    ZioBelin, Apr 3, 2012
    #4
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.