0

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.

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.