tags:

views:

200

answers:

4

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?

+5  A: 

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);
    }
Alan Jackson
+6  A: 

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;
 }
Lance Harper
You could probably simplify that to args.IsValid = (TextBox1.Text + TextBox2.Text).Length > 0 or something like that.
Fredrik Mörk
@Fredrik: He should add the lengths together, not the text itself. That makes it clearer. Though I think Lance's way is clearer still.
Brian
Yes, thanks for the clean-up!
Lance Harper
+3  A: 

In addition to creating server-side validation, you can use the ClientValidationFunction property on the CustomValidator to provide client-side validation as well. That might look something like this:

function(sender, args) {
    args.IsValid = document.getElementById('<%=TextBox1.ClientID%>').value != '' 
                   || document.getElementById('<%=TextBox2.ClientID%>').value != '';
}
bdukes
A: 

Onclientclick of your button or whatever submits your page call a javascript function like this

function valtxtbox(){


if (document.getElementById('<%=TextBox1.ClientID%>').value== '' && document.getElementById('<%=TextBox2.ClientID%>').value== '')
{

alert('You must enter in data!');
return false;
}
Eric
here you should have to put AND condition instead of OR
Muhammad Akhtar