Jack
Jack

Reputation: 7557

RequiredFieldValidator IsValid returning false on visible = false control

I want that when the textbox is visible = false, the RequiredFieldValidator shouldn't run.

This is my aspx code:

<asp:TextBox runat="server" ID="txtAmt" MaxLength="7" Style="width: 100px;"/>
                    <asp:RequiredFieldValidator ValidationGroup="ln" runat="server" ControlToValidate="txtAmt"
                        Display="Dynamic" ErrorMessage="Required" />

Now in my code behind

 protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
           txtAmt.Visible = false;
        }
    }

and yet in my button click handler, when I do a Page.IsValid, it returns false if textbox is empty. Any idea how to solve this issue?

Upvotes: 0

Views: 3117

Answers (2)

Shafqat Masood
Shafqat Masood

Reputation: 2570

using javascript you can achive this

<script type="text/javascript">
        function txtAmtOff()
        {
            document.getElementById("txtAmt").style.display = 'none';
            ValidatorEnable(document.getElementById("txtAmtValidator"), false);
        }
        function txtAmtOn()
        {
            document.getElementById("txtAmt").style.display = 'inline';
            ValidatorEnable(document.getElementById("txtAmtValidator"), true);
        }
    </script>

Upvotes: 0

Carlos Landeras
Carlos Landeras

Reputation: 11063

Just assign an ID to the validator and disable it.

 protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
           txtAmt.Visible = false;

         if(!txtAmt.visible) { txtamtValidator.Enabled=false};

        }
    }

Upvotes: 3

Related Questions