Two text fields are required: one or both

I have two text fields on an asp.net webpage, either one or both must be filled out. Both cannot be empty. How to create a validator for this in asp.net?

+5
source share
4 answers

For this you will need a CustomValidator .

Here are some examples demonstrating basic usage. The custom validator text will be displayed after calling IsValid in the submit callback, and some text will be displayed in 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 for

    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);
    }
+7
source

Try CustomValidator .

ServerValidate , :

void ServerValidation (object source, ServerValidateEventArgs args)
 {
    args.IsValid = TextBox1.Text.Length > 0 || TextBox2.Text.Length > 0;
 }
+7

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

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

Onclientclick of your button or something that submits your page calls 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;
}
-1
source

All Articles