Using RequiredFieldValidator to check if at least one of the two textboxes has some text inside?

Ashwin Singh picture Ashwin Singh · Jun 28, 2012 · Viewed 9.8k times · Source

I have two textboxes on my asp.net page and a submit button. How can I use a single or more RequiredFieldValidators to check if at least one of the two textboxes has some text inside on submit button click?

Answer

Ishan picture Ishan · Jun 28, 2012

Along with two text boxes add a CustomValidator and call server side validation.

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<br />
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="CustomValidator" OnServerValidate="CustomValidator_ServerValidate"></asp:CustomValidator>
<br />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />

Server side function

public void CustomValidator_ServerValidate(object source, System.Web.UI.WebControls.ServerValidateEventArgs args)
    {
        args.IsValid = true;

        if (TextBox1.Text == "" && TextBox2.Text == "")
        {
            CustomValidator1.ErrorMessage = "Enter value in at least one text Box";
            args.IsValid = false;

        }
    }

Hope this helps you.