user3378165 user3378165 - 4 months ago 14
Javascript Question

Jquery validation triggers but doesn't prevent the form submitting

I have an MVC project with Knockout.

I'm trying to validate my Resiter View using jquery validation.

This is the Register View:

<form data-bind="submit: register" id="formRegister">
<label>Email</label>
<input id="registerEmail" name="registerEmail" class="required email form-control" type="text" data-bind="value: registerEmail" />

<label>Password</label>
<input id="registerPassword" name="registerPassword" class="required form-control" type="password" data-bind="value: registerPassword" />

<label>Confirm Password</label>
<input id="registerPassword2" name="registerPassword2" class="required form-control" type="password" data-bind="value: registerPassword2" />

<button type="submit" class="btn btn-default">Register</button>
</form>


And the jquery:

<script>
$(function () {
$(document).ready(function () {
$("#formRegister").validate();
$.extend($.validator.messages, { required: "*", email: "Invalid email address." });
});
});
</script>


When I submit the form, the validaton is triggered but the form is also being submited.

Please advise.

Answer

You have to return false if form is not valid.

$(document).on("submit", "#formRegister", function(evt) {
      if(!$(evt.target).valid()) { return false; }
 });