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

I have two textboxes on an 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

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.


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

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

    <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);