2

I want to use an onlick event handler to validate some form fields using jquery Validate. To do this I have the following code:

<input type="text" id="Name" name="Name">  
<a class="btn btn-primary js-add-names" href="#">Add Names</a> 

<input type="text" id="Age" name="Age">
<a class="btn btn-primary js-add-ages" href="#">Add Age</a> 

<script>


   $(".js-add-names").click(function (e) {

     e.preventDefault();

     $("form").validate({
        rules: {
          Name: {
             required: true
          }
        },
        messages: {
          Name: "The Name is required"
        }

     });

     if (!$("form").valid()) {
        return;
     }

     //  otherwise do stuff but we dont want to submit form
   });


   $(".js-add-ages").click(function (e) {

     e.preventDefault();

     $("form").validate({
        rules: {
          Age: {
             required: true
          }
        },
        messages: {
          Age: "The Age is required"
        }

     });

     if (!$("form").valid()) {
        return;
     }

     //  otherwise do stuff but we dont want to submit form
   });

</script>

What I've noticed is that only one event handler works out the two based on whichever one was clicked first i.e. if I click the button with class js-add-names, the validation for that handler works as expected.

Now If I click the button with class js-add-ages having previously clicked js-add-names then the handler for js-add-age doesn't work and vis versa?

Any ideas why this is happening and what is the fix?


* UPDATE *

Further to suggestion by Sparky I have re-written the code as below but now when I click js-add-names, the validation for that handler works as expected

Now If I click the button with class js-add-ages having previously clicked js-add-names then the handler for js-add-age doesn't work becuase the validation has previously added a rule for input #Name. How do I reset the form or remove the rules each time the event handlers fire?

<form>
   <input type="text" id="Name" name="Name">  
   <a class="btn btn-primary js-add-names" href="#">Add Names</a> 

   <input type="text" id="Age" name="Age">
   <a class="btn btn-primary js-add-ages" href="#">Add Age</a> 

   // other inputs
   <input type="checkbox" name="CarOwner" value="Yes"> Car owner

   <input type="submit" value="Submit">
</form>

<script>

   $("form").validate();

   $(".js-add-names").click(function (e) {

     e.preventDefault();

     $("#Age").rules("remove");

     $("#Name").rules("add", {
        required: true,
        messages: {
            required: "The Name is required"
        }
     });

     if (!$("form").valid()) {
        return;
     }

     //  otherwise do stuff but we dont want to submit form
     //  ...

     //Reset input field
     $("#Name").val('');
   });


   $(".js-add-ages").click(function (e) {

     e.preventDefault();

     $("#Name").rules("remove");

     $("#Age").rules("add", {
        required: true,
        messages: {
            required: "The Age is required"
        }
     });

     if (!$("form").valid()) {
        return;
     }

     //  otherwise do stuff but we dont want to submit form
     //  ...

     //Reset input field
     $("#Age").val('');
   });

</script>
1
  • Do you want to validate one field by click or might validate 2 fields at the same time? Commented Nov 29, 2016 at 16:02

1 Answer 1

2

Any ideas why this is happening and what is the fix?

The .validate() method is only used for initializing the plugin on your form and therefore should only be called once when the page is loaded. Subsequent calls are always ignored. So when you use one click handler, you initialize the validate plugin, and the other call to .validate() in the other click handler will do nothing.

The fix...

  1. Call .validate() ONE time to initialize the plugin on your form.

  2. Do NOT call .validate() from a click handler since this is not the testing method; it's only the initialization method.

  3. Use the plugin's built-in submitHandler and invalidHandler functions for stuff you need to do when the form is valid and invalid.

  4. Since you appear to be using your click handlers to add fields/rules to an existing form, then use the .rules('add') and .rules('remove') methods to add and remove any rules dynamically.

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

3 Comments

Quote @adam78 : "How do I reset the form or remove the rules each time the event handlers fire?" ~ See my edits... use a .rules('remove').
I've added the .rules('remove') but now I've noticed the form is requiring a double click on all my form inputs and buttons?
@adam78, I am absolutely not seeing any behavior like that here... everything is working as expected without double-clicks: jsfiddle.net/yvop9t91

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.