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.

user1275232
  • 15
  • 1
  • 3
  • you can try the jquery validate plugin.[jquery-plugin-validation](http://bassistance.de/jquery-plugins/jquery-plugin-validation/),it can automatic validate when entered value. – zhengchun Mar 17 '12 at 03:19

2 Answers2

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>
emre nevayeshirazi
  • 18,983
  • 12
  • 64
  • 81
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";
    }
}
Community
  • 1
  • 1
IrishChieftain
  • 15,108
  • 7
  • 50
  • 91