Table of contents

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

 

To report the form errors.

$("#form")[0].reportValidity()

 

Example 1:

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

 

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>

 

I hope my examples will help you on how to force HTML 5 form validation on button click.