Thursday, 5 April 2012

Is it possible to make a radio button a required field? or Adding a required field to radio button


 yes, see the example below.

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

                <%--Creaint Items to be display in Radio Button List--%>

                <asp:ListItem Value="0">Male</asp:ListItem>

                <asp:ListItem Value="1">Female</asp:ListItem>

            </asp:RadioButtonList>

            <%--Creating RequiredFieldValidator control to validate RadioButtonList that we have created--%>

            <asp:RequiredFieldValidator runat="server" ID="radRfv" ControlToValidate="radio"  errormessage="Select One option"></asp:RequiredFieldValidator>



Either you can use initialvalue property required filed validator. which is like  

 <asp:RequiredFieldValidator runat="server" ID="radRfv" ControlToValidate="radio"  initialvalue="0" errormessage="Select one option"></asp:RequiredFieldValidator>

For radio buttons:

Radio Buttons do not support the Required Field Validator. You can
either have a button selected by default or employ javascript. Here's a
simple example that forces a user to select either a Male or Female radio
button. There are plenty of variations of this on the Internet if you do a
little digging:

if ( ( document.myForm.gender[0].checked == false ) && (
document.myForm.gender[1].checked == false ) )
{
alert ( "Please select either Male or Female" );
valid = false;
}

No comments:

Post a Comment