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
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. 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)
Such a nice post!! Spell to make someone feel the hurt they caused you