Asp – Two text boxes, either one or both are required

asp.net

I have two textboxes on an asp.net webpage, either one or both are required to be filled in. Both cannot be left blank. How do I create a validator to do this in asp.net?

Best Solution

You'd need a CustomValidator to accomplish that.

Here is some code demonstrating basic usage. The custom validator text will show after IsValid is called in the submit callback and some text will be displayed from the Response.Write call.

ASPX

    <asp:TextBox runat="server" ID="tb1" />
    <asp:TextBox runat="server" ID="tb2" />

    <asp:CustomValidator id="CustomValidator1" runat="server" 
      OnServerValidate="TextValidate" 
      Display="Dynamic"
      ErrorMessage="One of the text boxes must have valid input.">
    </asp:CustomValidator>

    <asp:Button runat="server" ID="uxSubmit" Text="Submit" />

Code Behind

    protected void Page_Load(object sender, EventArgs e)
    {
        uxSubmit.Click += new EventHandler(uxSubmit_Click);
    }

    void uxSubmit_Click(object sender, EventArgs e)
    {
        Response.Write("Page is " + (Page.IsValid ? "" : "NOT ") + "Valid");
    }

    protected void TextValidate(object source, ServerValidateEventArgs args)
    {
        args.IsValid = (tb1.Text.Length > 0 || tb2.Text.Length > 0);
    }