DEV Community

Cover image for Force HTML5 Form Validation using Button on Click in jQuery
Code And Deploy
Code And Deploy

Posted on

Force HTML5 Form Validation using Button on Click in jQuery

Originally posted @ https://codeanddeploy.com visit and download the sample code: https://codeanddeploy.com/blog/jquery/force-html5-form-validation-using-button-on-click-in-jquery

In this post, I will share a solution on how to Force HTML5 Form Validation without submitting the form in jQuery. If you need to use the button on click when submitting the form and want to use the native form validation.

To check if a form field is valid.

$('#form')[0].checkValidity(); // returns true/false
Enter fullscreen mode Exit fullscreen mode

To report the form errors.

$("#form")[0].reportValidity()
Enter fullscreen mode Exit fullscreen mode

Example 1:

$('#button').on('click', function() {
   if($("#form")[0].checkValidity()) {
      alert('success');
   } else {
      $("#form")[0].reportValidity()
   }
});
Enter fullscreen mode Exit fullscreen mode

Example 2:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>

    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {

            $("#button").on("click", function() {

                if($("#form")[0].checkValidity()) {
                    var title = $("#form [name='title']").val();

                    // ajax here
                } else {
                    $("#form")[0].reportValidity();
                }


            });
        })
    </script>
</head>
<body>

    <form id="form" method="post">
        <input type="text" name="title" placeholder="title" required>
        <button type="button" id="button">Submit</button>
    </form>

</body>
</html>
Enter fullscreen mode Exit fullscreen mode

I hope my examples will help you on how to force HTML 5 form validation on button click. I hope this tutorial can help you. Kindly visit here https://codeanddeploy.com/blog/jquery/force-html5-form-validation-using-button-on-click-in-jquery if you want to download this code.

Happy coding :)

Top comments (1)

Collapse
 
aarichill profile image
AaricHill