Home > ASP.Net > Validate Group of RadioButton

Validate Group of RadioButton


Hi

try this example to validate Group of RadioButton using CustomValidator Control with Client and Server Side

<asp:RadioButtonList ID="RadioButtonList1" runat="server">
            <asp:ListItem>north</asp:ListItem>
            <asp:ListItem>west</asp:ListItem>
        </asp:RadioButtonList>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
            ControlToValidate="RadioButtonList1" ErrorMessage="RequiredFieldValidator">
        </asp:RequiredFieldValidator>

2. Without RadioButtonList and if you want a group radiobutton insteads, you can also implement it by CustomValidator.

<script language="javascript" type="text/javascript" >
function CustomValidator1_ClientValidate(source,args)
{  
    if(document.getElementById("<%= RadioButton1.ClientID %>").checked || document.getElementById("<%= RadioButton2.ClientID %>").checked)
    {
        args.IsValid = true;
    }
    else
    {
        args.IsValid = false;
    }
   
}
//-->
</script>
<body>
    <form id="form1" runat="server">
    <div>  
    <asp:RadioButton ID="RadioButton1" runat="server" GroupName="location" Text="north" />
    <asp:RadioButton ID="RadioButton2" runat="server" GroupName="location" Text="west" />
    <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
    <asp:CustomValidator id="CustomValidator1" runat="server" Display="Dynamic" ErrorMessage="please choose" ClientValidationFunction="CustomValidator1_ClientValidate" OnServerValidate="CustomValidator1_ServerValidate"></asp:CustomValidator>
    </div>
    </form>
</body> 

using Server Side :-
 

   protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
    {
        args.IsValid = RadioButton1.Checked || RadioButton2.Checked;
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            //validate is successful.
        }
    }

Hope this can help.

Advertisements
Categories: ASP.Net
  1. Achala
    June 21, 2011 at 10:34 am

    THANKS for the sample code ,I’m a student from Sri Lanka.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: