Skip to content

Instantly share code, notes, and snippets.

@khoand0000
Last active November 9, 2015 23:44
Show Gist options
  • Save khoand0000/b46d010c362b0ddc68d9 to your computer and use it in GitHub Desktop.
Save khoand0000/b46d010c362b0ddc68d9 to your computer and use it in GitHub Desktop.
Why Parsley permit submit even form is invalid, using Parsley by javascript?
  • HTML file
<form id="my-form">
<input type="email" name="email" required/>
<button type="submit">submit</button>
</form>
  • Javascript file
$('#my-form').parsley(); // (1)
$('#my-form').submit(function(e) { // (2)
    // do something
});
  • The form is always submitted when click submit button even email is empty or invalid format. Why? Because Parsley will add novalidate attribute into form when (1) and listen submit event of the form, so when click submit button, the form will trigger my submit() function (2) first, after that, parsley will check form is valid or not, if it is not, parsley will prevent submit event. But at the time, my submit() is processed. To prevent the case, modify my submit():
$('#my-form').submit(function(e) {
    if (!$(this).parsley().isValid()) {
        e.preventDefault();
        return;
    }
  
    // do something
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment