0

I have two asp:TextBox. User needs to enter value in at-least one of the text boxes. Please let me know how to validate to make sure data is entered in atleast one of the boxes. Thanks.

1
  • you can try the jquery validate plugin.jquery-plugin-validation,it can automatic validate when entered value. Commented Mar 17, 2012 at 3:19

2 Answers 2

1

You can use CustomValidator to validate your TextBoxes.

protected void ValidateBoxes(object sender, ServerValidateEventArgs e)
{
    if (TextBox1.Text == "" && TextBox2.Text == "")
        e.IsValid = false;
    else
        e.IsValid = true;
}

You should also specify your validator at .aspx page.

<asp:CustomValidator ID="Validator1" runat="server" ControlToValidate="TextBox1"
                     OnServerValidate="ValidateBoxes" 
                     ErrorMessage="• Enter Text" ValidationGroup="check"
                     Display="None">
</asp:CustomValidator>

Remember that the ValidationGroup property of both CustomValidator and the Button that triggers post back should be same. So, your button should be some thing like below.

<asp:Button ID="Button1" runat="server" Text="Hey"
            ValidationGroup="check"
            OnClick="Operation"> 
</asp:Button>
Sign up to request clarification or add additional context in comments.

Comments

0

Use a CustomValidator and in your code-behind you can set the IsValid property to true only if both TextBoxes are not empty:

http://asp.net-tutorials.com/validation/custom-validator/

http://p2p.wrox.com/asp-net-1-0-1-1-basics/19729-custom-validator-two-text-box.html

Something similar with client-side solutions:

asp.net validate textbox - at least one text box must have data in

Alternative solution using two RequiredValidators:

void Button_Click(Object sender, EventArgs e) 
{
    if (TextBoxRequiredValidator1.IsValid && TextBoxRequiredValidator2.IsValid)
    {
      // Process page
    }
    else
    {
      MessageLabel.Text = "Both TextBoxes must be filled";
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.