html5 adds long overdue form validation.
I've been tinkering with it a bit and
- I quite like the constraint validation API (validityState object,
setCustomValidity)
- I have mixed feelings about the browser UI for invalid fields
(speech bubbles)
- I really want more events.
This post is about events.
The only new event added is 'invalid'. This is fired either when
"checkValidityState()" is called for a field, and it is invalid; or
when the form is submitted. When I compare this to the :invalid CSS
selector, it seems to me that browsers know that fields are invalid
some time, but are very selective about whether they fire an event.
For example, if you enter an invalid value, the field border might
turn red on blur (the :invalid css selector now works), but no
'invalid event' is triggered until checkValidityState() or form
submission.
There is never a 'valid' event. This makes customising the UI a little
more difficult. You have to bind to the 'change' event and then check
the validityState object. Which you can do for 'invalid' too. Why have
an invalid event and not a valid event? I would like to display a
message on invalid, and hide that alert on valid.
Another common UI technique is to display a summary of errors when a
form is submitted. There is no event to help with this, and html5
actually makes it harder to detect by stopping the submit event.
Invalid fields prevent the submit event from being triggered, see step
5 of the form submission algorithm here:
http://www.whatwg.org/specs/web-apps/current-work/multipage/association-of-controls-and-forms.html#form-submission-algorithm
Instead you need to do something like:
- watch when buttons are clicked, and guess that means form submission
- catch and cancel all 'invalid' events, so the submit event is
triggered, which you then catch and cancel to stop form submission
- display the summary when an 'invalid' event happens, remembering
that multiple invalid fields trigger multiple events, or these events
might be triggered by checkValidityState()
Did I mention that invalid events do not bubble? You have to .bind()
to every form field, you can't use .live() in jquery. This is
disappointing.
Compare this to xforms submission, which triggers 'xforms-submit-
invalid' event when form fields are invalid.
See step 4:
http://www.w3.org/TR/xforms/#submit-evt-submit
I'd really like to be able to bind to events for valid (field that was
invalid has become valid) and submit-error (submit was attempted, but
failed).
I'd like to hear if others have had similar findings. If you've tried
out the forms validation in html5, what did you think?