yarek
yarek

Reputation: 12034

how to validate an HTML5 form and not post the form?

I have a form with some html attributes like:

<form>
      <label>Full  Name</label>

      <input type="text" name="firstname" class="span3" required="required">
      <label>Email Address</label>
      <input type="email" name="email" class="span3" required="required">
      <label>Username</label>
      <input type="text" name="username" class="span3" required="required">
      <label>Password</label>

when user clicks on button, I want the html5 to apply validattion rules.

If the validations rules are OK, then do not submit the form, but use some $_POST ajax

Any idea ?

Upvotes: 0

Views: 65

Answers (2)

Paul Rad
Paul Rad

Reputation: 4882

Something like this

$('form').on('submit', function(e) {
 if (e.target.checkValidity() === false)
 {
   e.preventDefault(); // disable the "normal" action of submit
 }
});

Upvotes: -1

adeneo
adeneo

Reputation: 318162

checkValidity() will validate the form using the native HTML5 validation :

$('form').on('submit', function(e) { // or on button click ?
    e.preventDefault()

    var valid = e.target.checkValidity();

    if (valid) {
        // do ajax
    }
});

From MDN:

On HTMLFormElement objects, the checkValidity() method, which returns true if all of this form element's associated elements that are subject to constraint validation satisfy their constraints, and false if any do not.

Note that it might not be supported in all browsers.

Upvotes: 5

Related Questions