2

I have a form, and when is submitted I prevent it with e.preventDefault(), but I still want the browser to validate the required fields before I make the AJAX call.

I don't want to get fancy with javascript validation, I just want the browser to validate the required fields (HTML5).

How can I achieve this?

Jonwd
  • 635
  • 10
  • 24
  • Any consideration/fallback for browsers that don't support HTML5 form validation? If the browser supports HTML5 validation, you shouldn't need to add anything (as long as the proper attributes are there). Something like this: http://jsfiddle.net/girlie_mac/X6Uuc/ – Jack Feb 26 '14 at 02:43
  • 1
    Duplicate of: http://stackoverflow.com/questions/11866910/how-to-force-a-html5-form-validation-without-submitting-it-via-javascript-jquery?rq=1 – Jonwd Feb 26 '14 at 02:51
  • @JackPattishallJr. Yes, but right now I don't have time. And since I'm using a framework on server side, fields are still validated. Thanks. – Jonwd Feb 26 '14 at 02:52

2 Answers2

3

It works, even if you don't do the checkValidity check. In chrome, it won't call the submit function on the form if form is not valid:

$(document).ready(function(){
    $("#calendar_form").submit(function(e){
        e.preventDefault();
        calendarDoAjax();
    });

    function calendarDoAjax(){
        var proceed = false;
        if( $("#calendar_form")[0].checkValidity ){
            if ($("#calendar_form")[0].checkValidity()) {
                proceed = true;
            }
        }else{
            proceed = true;
        }
        if (proceed) {
            //Do ajax call
        }
    }

});
Jonwd
  • 635
  • 10
  • 24
0

Add this in the end of your submit function:

if (evt && evt.preventDefault) {
    evt.preventDefault();
} else if (event) {
    event.returnValue = false;
}

return false;

And pass the var evt in your function like this:

function(evt) { /* Your Code */ }
CIRCLE
  • 4,501
  • 5
  • 37
  • 56
  • Doesn't work, I just tried. This one works tho: http://stackoverflow.com/questions/11866910/how-to-force-a-html5-form-validation-without-submitting-it-via-javascript-jquery?rq=1 – Jonwd Feb 26 '14 at 02:51