Forum Moderators: open

Message Too Old, No Replies

Validation of a RadioButton with GroupName

         

IntegrityWebDev

3:44 pm on Mar 5, 2010 (gmt 0)

10+ Year Member



I think I'm in my final stage of validating this form...I have a group of RadioButtons and I need the end user to select one.

For layout reasons I couldn't use a list so I had to group them with GroupName. I know you cannot validate a group of RadioButtons with normal validate.

I'm trying to figure out a way around this. Can you validate a hidden field? If so I could maybe use the radio buttons to fill in a value on a hidden field, then validate that hidden field. Or maybe set a text field to invisible (or hide with CSS), and have the radios populate that and check that field?

Everything else validates with a summary validation (where an alert box pops up with a list of all fields not filled in) and i really need this answer to be included in that list.

What are your thoughts?

Thanks all,
Chris

marcel

9:50 am on Mar 7, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



For layout reasons I couldn't use a list so I had to group them with GroupName.

Just in case you haven't tried this already, you can influence the layout of the RadioButtonList with RepeatColumns, RepeatDirection and RepeatLayout. And if that doesn't work you could try styling with CSS.

Otherwise, you could use a custom validator, here is an example:

HTML
<asp:RadioButton Text="1" ID="RadioButton1" GroupName="myGroup" runat="server" />
<asp:RadioButton Text="2" ID="RadioButton2" GroupName="myGroup" runat="server" />
<asp:RadioButton Text="3" ID="RadioButton3" GroupName="myGroup" runat="server" />
<asp:RadioButton Text="4" ID="RadioButton4" GroupName="myGroup" runat="server" />
<asp:RadioButton Text="5" ID="RadioButton5" GroupName="myGroup" runat="server" />
<asp:CustomValidator ID="cvRadioButtonGroup" runat="server" ErrorMessage="* make a selection" onservervalidate="cvRadioButtonGroup_ServerValidate" />


Code Behind
protected void cvRadioButtonGroup_ServerValidate(object source, ServerValidateEventArgs args)
{
bool itemSelected = false;
// get all radio buttons on the page
foreach (Control c in form1.Controls)
{
if (c is RadioButton)
{
RadioButton rb = (RadioButton)c;
if (rb.GroupName == "myGroup" && rb.Checked == true)
{
itemSelected = true;
}
}
}
args.IsValid = itemSelected;
}

IntegrityWebDev

8:28 pm on Mar 7, 2010 (gmt 0)

10+ Year Member



Thanks Marcel...I will play around with that!