Developer
Developer

Reputation: 8636

Issue with radio buttons while firing Validations

Hi all i have my form with some controls as follows

2 Radio buttons 1 Text Box, 1 Required field validator and a button

I wrote my sample code in such a way that if one radio button is selected i will enable or disable the text box that i will have.

I am having a required field validator which was set for text box available. Now what i need is when the control was disabled i don't want to perform the validation for this is it possible to do

Sample code

protected void RadioButton1_CheckedChanged(object sender, EventArgs e)
{
    TextBox1.Enabled = true;
}
protected void RadioButton2_CheckedChanged(object sender, EventArgs e)
{
    TextBox1.Enabled = false;
}

My design

<form id="form1" runat="server">
<div>
    <asp:RadioButton ID="RadioButton1" runat="server" AutoPostBack="True" GroupName="g"
        OnCheckedChanged="RadioButton1_CheckedChanged" ValidationGroup="g1" />
    <asp:RadioButton ID="RadioButton2" runat="server" AutoPostBack="True" GroupName="g"
        OnCheckedChanged="RadioButton2_CheckedChanged" />
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1"
        ErrorMessage="RequiredFieldValidator" ValidationGroup="g1"></asp:RequiredFieldValidator>
    <asp:Button ID="Button1" runat="server" Text="Button" ValidationGroup="g1" /></div>
</form>

Validation should apply only when the control was enabled

Upvotes: 0

Views: 629

Answers (2)

Developer
Developer

Reputation: 8636

I got this and works well for me

protected void RadioButton1_CheckedChanged(object sender, EventArgs e)
{
    TextBox1.Enabled = true;
    Button1.CausesValidation = true;
}
protected void RadioButton2_CheckedChanged(object sender, EventArgs e)
{
    Button1.CausesValidation = false;
    TextBox1.Enabled = false;
}

Upvotes: 0

Fr&#233;d&#233;ric Hamidi
Fr&#233;d&#233;ric Hamidi

Reputation: 262939

Validators have an Enabled property that you can use:

protected void RadioButton1_CheckedChanged(object sender, EventArgs e)
{
    TextBox1.Enabled = RequiredFieldValidator1.Enabled = true;
}

protected void RadioButton2_CheckedChanged(object sender, EventArgs e)
{
    TextBox1.Enabled = RequiredFieldValidator1.Enabled = false;
}

Upvotes: 1

Related Questions