One way to trigger actual form submission is by using this code snippet.
When an actual form submission occurs, it will execute the checkValidity
function, display bubble errors, and call necessary event handlers for invalid input fields.
To prevent the form from actually submitting, you can attach a submit
event handler to the <form>
element that stops the default action, allowing you to perform an AJAX call instead.
This method relies on the fact that the submit
event is only triggered when all form constraints are met (i.e., valid data). Therefore, there is no need to explicitly call
checkValidity</code.</p>
<p><strong>Update: 11/7/12 - Responding to feedback.</strong></p>
<p>By "actual form submission," I simply mean a traditional submission with a submit button as opposed to AJAX. This is necessary for displaying native bubbles and shifting focus to the correct form elements. Even if no submit button is visible, you can use a hidden one to trigger submission, as shown in this <a href="http://jsfiddle.net/tj_vantoll/rwgk9/" rel="noreferrer">example</a>.</p>
<p>Although this workaround may not be ideal, it is compatible with <a href="http://caniuse.com/#feat=form-validation" rel="noreferrer">all major browsers</a>. The reason for using this hack instead of <code>form.submit()
is that the latter does not trigger native validation. It seems strange that
form.submit()
skips constraint validation, considering the spec mandates running it during form submission (source).
It's worth mentioning that checkValidity
follows the same algorithm as a regular form submission, giving developers the flexibility to customize error handling. For instance, you can disable default bubbles and create your own design like in this demo.