HTML5 validation before ajax submit HTML5 validation before ajax submit ajax ajax

HTML5 validation before ajax submit


If you bind to the submit event instead of click it will only fire if it passes the HTML5 validation.

It is best practice to cache your jQuery selectors in variables if you use it multiple times so you don't have to navigate the DOM each time you access an element. jQuery also provides a .serialize() function that will handle the form data parsing for you.

var $contactForm = $('#contactForm');$contactForm.on('submit', function(ev){    ev.preventDefault();    $.ajax({        url: "scripts/mail.php",        type:   'POST',        data: $contactForm.serialize(),        success: function(msg){            disablePopupContact();            $("#popupMessageSent").css("visibility", "visible");        },        error: function() {            alert("Bad submit");        }    });});


By default, jQuery doesn't know anything about the HTML5 validation, so you'd have to do something like:

$('#submit').click(function(){    if($("form")[0].checkValidity()) {        //your form execution code    }else console.log("invalid form");});


If you are using HTML5 form validation you'll have to send the ajax request in the form's submit handler. The submit handler will only trigger if the form validates. What you're using is a button click handler which will always trigger because it has no association with form validation. NOTE: not all browsers support html5 form validation.