I'm using HTML5 for validating fields. I'm submitting the form using JavaScript on a button click. But the HTML5 validation doesn't work. It works only when then input type is submit
. Can we do anything other than using JavaScript validation or changing the type to submit
?
This is the HTML code:
<input type="text" id="example" name="example" value="" required> <button type="button" onclick="submitform()" id="save">Save</button>
I'm submitting the form in the function submitform()
.
You can now use the HTMLFormElement. reportValidity() method, at the moment it's implemented in most browsers except Internet Explorer (see Browser compatibility at MDN). It reports validity errors without triggering the submit event and they are shown in the same way.
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 HTML5, we can create a form with built in validation (i.e. no javascript required). Earlier, we were using JAVASCRIPT to control form validation.
The HTML5 form validation process is limited to situations where the form is being submitted via a submit button. The Form submission algorithm explicitly says that validation is not performed when the form is submitted via the submit()
method. Apparently, the idea is that if you submit a form via JavaScript, you are supposed to do validation.
However, you can request (static) form validation against the constraints defined by HTML5 attributes, using the checkValidity()
method. If you would like to display the same error messages as the browser would do in HTML5 form validation, I’m afraid you would need to check all the constrained fields, since the validityMessage
property is a property of fields (controls), not the form. In the case of a single constrained field, as in the case presented, this is trivial of course:
function submitform() { var f = document.getElementsByTagName('form')[0]; if(f.checkValidity()) { f.submit(); } else { alert(document.getElementById('example').validationMessage); } }
I may be late, but the way I did it was to create a hidden submit input, and calling it's click handler upon submit. Something like (using jquery for simplicity):
<input type="text" id="example" name="example" value="" required> <button type="button" onclick="submitform()" id="save">Save</button> <input id="submit_handle" type="submit" style="display: none"> <script> function submitform() { $('#submit_handle').click(); } </script>
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