Reputation: 15
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.
Upvotes: 0
Views: 8878
Reputation: 19241
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>
Upvotes: 1
Reputation: 15253
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";
}
}
Upvotes: 0