views:

199

answers:

2

Hi,

I currently have 3 textbox controls on my page.

I also have a required valdiator of each of the textboxes. However I only want the validator for a textbox to fire if there is text in either of the other 2 textboxes. If all 3 textboxes are empty then no validators should fire.

Is there any way I can do this in javascript/jquery as I want the user to get the best experience possible.

Any help would be greatly appreciated.

Thanks in advance.

A: 

For client-side validation take a look at this plugin: http://plugins.jquery.com/project/validate

This will allow you to write your own validation methods.

David Neale
+1  A: 

If you are using WebForms I would go with a custom validator in this case for each textbox (you could do with just one though):

<asp:CustomValidator id="cvalTextBox1" runat="server" Display="*"
        ErrorMessage="Required: TextBox1"
        ClientValidationFunction="ValidateRequiredTextBox1" ValidateEmptyText="true"  
        ControlToValidate="txtTextBox1"></asp:CustomValidator>

Then implement your javascript (using jQuery):

<script>
    function ValidateRequiredTextBox1(source, arguments)
    {
        if ((jQuery.trim($("#<%= txtTextBox1.ClientID %>").val()) == "") &&
            ((jQuery.trim($("#<%= txtTextBox2.ClientID %>").val()) != "") ||
             (jQuery.trim($("#<%= txtTextBox3.ClientID %>").val()) != "")))
        {
            arguments.IsValid = false;
        }
        else
        {
            arguments.IsValid = true;
        }
    }
</script>

So this will work for 1 textbox (assuming you want 1 validator for each box to display a * or something). You will need 3 functions total to implement all 3 textboxes or you could just use one validator for all with minor tweaks to the above javascript.

Kelsey
Thank you, I used this with some minor modifications. It worked a treat.
Zaps