HTML5 validation before ajax submit

Solution 1:

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");
        }
    });
});

Solution 2:

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");
});

Solution 3:

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.

Solution 4:

I prefer using the jQuery submit handler, you will still get the response to your form with the following method.

jQuery('#contactForm').on('submit', function (e) {
    if (document.getElementById("contactForm").checkValidity()) {
        e.preventDefault();
        jQuery.ajax({
            url: '/some/url',
            method: 'POST',
            data: jQuery('#contactForm').serialize(),
            success: function (response) {
                //do stuff with response
            }
        })
    }
    return true;
});