javascript - jQuery Validate using onclick handler not working? -
i want use jquery validate validate form fields using anchor onclick handler follows doesn't seem 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 required", enddate: "the end date required" } }); if (!validator.valid()) { console.log("invalid"); return; } // otherwise stuff dont want submit form }); </script> i want validate fields , if valid other stuff inside handler dont want submit form have button submitting form. validator.valid() function in above true. when submit main button dont need validate above fields not mandatory - client side interactivity need validate above fields.
is there way can achieve above?
your
if (!validator.valid()) { console.log("invalid"); return; } should be
if (!$("form").valid()) { console.log("invalid"); return; } your main problem var validator = $("form").validate({ function not returning boolean. try logging return value, see object being returned not boolean.
.validate() doesn't return boolean, sets validation.
to determine whether <form> or input element valid call .valid() boolean result.
hence above if (!validator.valid()) not work & never execute console.log("invalid"); line.
check codepen
Comments
Post a Comment