Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enable/Disable Required field validator from cs page?

I have two TextBox and two Buttons in my page.

One is hidden and the other one is displayed.

When I click the Button1, it will save data of the two TextBox and will validate each TextBox by the RequiredFieldValidator.

Then when I click Button2, it will just hide itself (Button2) and will show the hidden TextBox.

Both TextBox has RequiredFieldValidator validating against Button1's Event click.

Now my issue is when I simply enter text to the 1st TextBox and click save, the button click is validating the required field for hidden field. I just want to validate the 2 textbox when it is showing.

How can I avoid this?

like image 268
Rahul Chowdhury Avatar asked Apr 05 '13 06:04

Rahul Chowdhury


People also ask

How do I turn off required field validator?

Well you can simple use the Enabled="false" property of RequiredFieldValidator . Your markup would look something like this based on your Question.

What is enable or disable required field validator in asp net?

Use ValidatorEnable function from the Asp.net javacsript Script Library to Enable/Disable the validators on client side. Sometimes you may need to enable/disable validators on client side. you can easily do this using ValidatorEnable function in the Asp.net javacsript Script Library.

Why do we need required field validator?

ASP.NET RequiredFieldValidator Control This validator is used to make an input control required. It will throw an error if user leaves input control empty. It is used to mandate form control required and restrict the user to provide data.


2 Answers

Well you can simple use the Enabled="false" property of RequiredFieldValidator.

Your markup would look something like this based on your Question.

<asp:TextBox runat="server" ID="tb1"></asp:TextBox>
<asp:RequiredFieldValidator runat="server" ID="rfv1" ControlToValidate="tb1" ErrorMessage="*" ValidationGroup="gvSave">
</asp:RequiredFieldValidator>

<asp:TextBox runat="server" ID="tb2" Visible="false"></asp:TextBox>
<asp:RequiredFieldValidator runat="server" ID="rfv2" ControlToValidate="tb2" ErrorMessage="*" Enabled="false" ValidationGroup="gvSave">
</asp:RequiredFieldValidator>

<asp:Button runat="server" ID="btn1" Text="Save" onclick="btn1_Click" ValidationGroup="gvSave"/>
<asp:Button runat="server" ID="btn2" Text="Show" onclick="btn2_Click" />

And your codebehind like this:

protected void btn2_Click(object sender, EventArgs e)
{
    tb2.Visible = true;
    rfv2.Enabled = true; // Enables the second requiredfieldvalidator
}

protected void btn1_Click(object sender, EventArgs e)
{
  // your Saving code here
}
like image 92
Praveen Nambiar Avatar answered Sep 19 '22 21:09

Praveen Nambiar


use the ValidationGroup="group" property to button and assign validation group to text on which you want to validate. Hope it will help

like image 25
Vijay Singh Rana Avatar answered Sep 19 '22 21:09

Vijay Singh Rana