Search code examples
jqueryhtmlvalidation

How to force an HTML form to validate without submitting it via jQuery


I have this form in my app and I will submit it via AJAX, but I want to use HTML 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

  • 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
    

    Show html5 built-in error

    if (! $('#myForm')[0].checkValidity()) {
          $('#myForm')[0].reportValidity()
    }
    

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