Anyone who know how I can trigger the standard HTML5 validation in a form without using a submit button? (JavaScript or jQuery).
I do not want to send POST/GET
request, only do the validation.
1. Using HTML5 built-in functionality. HTML5 provides this feature of form validation without using JavaScript. Form elements will have validation attributes added, which will enable the form validation for us automatically.
To ignore HTML validation, you can remove the attribute on button click using JavaScript. Uer removeAttribute() to remove an attribute from each of the matched elements.
Using built-in form validationOne of the most significant features of HTML5 form controls is the ability to validate most user data without relying on JavaScript. This is done by using validation attributes on form elements.
After some research, I've came up with the following code that should be the answer to your question. (At least it worked for me)
Use this piece of code first. The $(document).ready
makes sure the code is executed when the form is loaded into the DOM:
$(document).ready(function() { $('#theIdOfMyForm').submit(function(event){ if(!this.checkValidity()) { event.preventDefault(); } }); });
Then just call $('#theIdOfMyForm').submit();
in your code.
UPDATE
If you actually want to show which field the user had wrong in the form then add the following code after event.preventDefault();
$('#theIdOfMyForm :input:visible[required="required"]').each(function() { if(!this.validity.valid) { $(this).focus(); // break return false; } });
It will give focus on the first invalid input.
You can use reportValidity, however it has poor browser support yet. It works on Chrome, Opera and Firefox but not on IE nor Edge or Safari:
var myform = $("#my-form")[0]; if (!myform.checkValidity()) { if (myform.reportValidity) { myform.reportValidity(); } else { //warn IE users somehow } }
(checkValidity has better support, but does not work on IE<10 neither.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With