Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two text boxes, either one or both are required

Tags:

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?

like image 846
DanH Avatar asked Jun 03 '09 21:06

DanH


2 Answers

Try a CustomValidator.

You'll need to create a method that does the following to handle the ServerValidate event:

void ServerValidation (object source, ServerValidateEventArgs args)
 {
    args.IsValid = TextBox1.Text.Length > 0 || TextBox2.Text.Length > 0;
 }
like image 45
Lance Harper Avatar answered Sep 21 '22 05:09

Lance Harper


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);
    }
like image 97
Alan Jackson Avatar answered Sep 20 '22 05:09

Alan Jackson