1

I want to use jQuery Validate to validate some form fields using a anchor onclick handler as follows but it doesn't seem to work?

<input type="text" id="StartDate" name="StartDate">  
<input type="text" id="EndDate" name="EndDate"> 

<a class="btn btn-primary js-add" href="#">Add</a> 




 <script>
   $(document).on('click', '.js-add', function (e) {
       e.preventDefault();

       var validator = $("form").validate({
          rules: {
              StartDate: {
                 required: true
              },
              EndDate: {
                 required: true
              }
          },
          messages: {
              StartDate: "The Start Date is required",
              EndDate: "The End Date is required"
          }

       });

      if (!validator.valid()) {
          console.log("invalid");
          return;
      }

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

 </script>

I want to validate the fields and if they are valid do some other stuff inside the handler but I dont want to submit the form as I have another button for submitting the form. The validator.valid() function in the above is always true. When I submit the main button i dont need to validate the above fields as they are not mandatory - this is just for some client side interactivity that i need to validate the above fields.

is there any way I can achieve the above?

1
  • Wouldn't this work? submitHandler: function(form) { /* do anything except form.submit();*/ } Commented Nov 8, 2016 at 12:36

2 Answers 2

1

Your

  if (!validator.valid()) {
      console.log("invalid");
      return;
  }

should be

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

Your main problem is var validator = $("form").validate({ function is not returning a boolean. try logging return value, you will see an object being returned not a boolean.

.validate() doesn't return a boolean, it sets up validation.

To determine whether a <form> or input element is valid you call .valid() to get a boolean result.

Hence your above if (!validator.valid()) will not work & thus it never execute the console.log("invalid"); line.

Check this Codepen

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

Comments

0

add these attribute to input element

data-val="true" data-val-required="your error message"

then run this code on click of your anchor

$(this).validate();

your must also refrence jquery.validate.js

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.