How to force a html5 form validation without submitting it via jQuery

I have this form in my app and I will submit it via AJAX, but I want to use HTML5 for client-side validation. So I want to be able to force the form validation, perhaps via jQuery.

I want to trigger the validation without submitting the form. Is it possible?


Solution 1:

To check whether a certain field is valid, use:

$('#myField')[0].checkValidity(); // returns true|false

To check if the form is valid, use:

$('#myForm')[0].checkValidity(); // returns true|false

If you want to display the native error messages that some browsers have (such as Chrome), unfortunately the only way to do that is by submitting the form, like this:

var $myForm = $('#myForm');

if (!$myForm[0].checkValidity()) {
    // If the form is invalid, submit it. The form won't actually submit;
    // this will just cause the browser to display the native HTML5 error messages.
    $myForm.find(':submit').click();
}

Keep in mind that, HTML5 validation is not supported in all browsers till now.

Solution 2:

below code works for me,

$("#btn").click(function () {

    if ($("#frm")[0].checkValidity())
        alert('sucess');
    else
        //Validate Form
        $("#frm")[0].reportValidity()

});