checkValidity to update UI
Time has moved on since 2012 and there is now a reportValidity()
method.
The
HTMLFormElement.reportValidity()
method returnstrue
if the element's child controls satisfy their validation constraints. Whenfalse
is returned, cancelableinvalid
events are fired for each invalid child and validation problems are reported to the user.
Further details at MDN.
This works in Chrome (40+), Edge (17+), Firefox (49+), Opera and Safari, but not IE.
Simply trigger an actual form submission - http://jsfiddle.net/tj_vantoll/ZN29S/.
An actual form submission will run checkValidity
, show the bubble errors, call invalid
event handlers as necessary, etc.
To ensure that the form doesn't actually submit you simply need to attach a submit
event handler to the <form>
that prevents the default action, then do the AJAX call.
This works because the submit
event will not be fired unless a form has been met all of its constraints (i.e. has valid data). Therefore an explicit call to checkValidity
isn't necessary.
Edit (11/7/12) to addresses comments.
By an actual form submission in this case I was simply referring to a non-AJAX submission done with a submit button. To get the native bubble to display and the focus to change to the appropriate form element this is the only way to accomplish this. If there is no submit button present you can make a hidden one and use that to trigger the submission; it will still work.
I would agree that this approach is less than ideal but it does work in all supporting browsers. The only reason this hack is used rather than calling form.submit()
is because form.submit()
does not trigger the native validation. To me the issue here is not that there is no API to trigger the validation, but rather that calling form.submit()
does not. The spec says that constraint validation should be run whenever "the user agent is required to statically validate the constraints of form element form". I do not know why calling form.submit()
would not apply.
It should be noted that checkValidity
DOES run through the same algorithm as a native form submission. Therefore you are free to turn off the default bubbles and implement your own. For example something like this.