Sunday, July 15, 2012

How to validate RadioButton using C#


Validating radio button in ASP.NET is not very tough but new programmers always get confused about this and ask the questions in forum for the help. So I thought I will write a simple article related to this topic.

Here I am going to use JavaScript to validate the RadioButton.

First we will create the RadioButton.

<asp:Label ID="Label1" text ="Please select one of your favorite fruits" runat="server"></asp:Label>

<asp:RadioButtonList ID="radiobutton1" runat="server">

<asp:ListItem Text="A.Apples">Apple</asp:ListItem>

<asp:ListItem Text="B.Banana">Banana</asp:ListItem>

<asp:ListItem Text="c.cherry">Orange</asp:ListItem>

<asp:ListItem Text="D.Dates">Grapes</asp:ListItem> </asp:RadioButtonList>

<asp:Button ID="btnSubmit" runat="server" onclick="btnSubmit_Click"

Text="Submit" />

If you look at the above code I have created a RadioButtonList with 4 RadioButtons and a Button.

Now we will write the JavaScript to validate the RadioButtonList

<script type="text/javascript">

function rdValidate()


var rd = document.getElementsByName('radiobutton1')

for (var i = 0; i < rd.length; i++)


if (rd[i].checked)


return true;



alert("Please select an option");

return false;



Next we will call the JavaScript function to validate the RadioButtonList on Button Click Event.

protected void btnSubmit_Click(object sender, EventArgs e)


ClientScript.RegisterStartupScript(GetType(), "Alert", "<script>rdValidate();</script>");


That’s it. Now you can run your application and click on the button click event without selecting the RadioButton. You will get the alert message like in below screen print.

Validate Radio Button using JavaScript

Please post your query if you have any in below comment section.

Thanks for reading this article.

No comments: