HTML and CSS Reference
In-Depth Information
Element validity
Individual form fields, along with having the checkValidity
method, also have a validity DOM attribute that returns a
ValidityState object. There are a number of state attributes
on the validity object, but the simplest and most important is
the valid attribute. This value can be tested using JavaScript
to drive a bespoke validation feedback system.
If we hook into the submit event handler on our form, we can
manually loop through all the input fields and check the valid-
ity object. But what happens if the field has no validation rules?
Yo u ' r e i in l u c k : T h e A P I p r o v i d e s a willValidate attribute that we
can test to see whether we should or shouldn't try to validate
this particular field. Here's a (contrived) example:
var email = document.getElementById('email');
if (email.willValidate) {
if (!email.validity.valid) {
alert(“Yarr, ye old email be invalid”);
Once you have the individual form field's validation state,
you could pull in any custom messages set via element.
validationMessage or test the different validity states, which also
include valueMissing , typeMismatch , patternMismatch , tooLong ,
rangeUnderflow , rangeOverflow , stepMismatch , and customError .
What's particularly important is that you disable the native brows-
er's validation behaviour. By adding the novalidate attribute to
the form element, as you'll see next, it disables the validation
feedback, but in fact the JavaScript API is still available and you
are still able to check the validity state on the fields. This means
you can have full control of the error feedback process.
NoTE It's worth noting
that <fieldset> ele-
ments also have the validity
attribute, but they don't do any-
thing. The validity attribute is
always true. You can also call
the checkValidity method
on fieldsets, but again, nothing
happens in the current browsers
that support custom validation.
Avoiding validation
The last question we need to answer is: What if you want to
submit the form—but you don't want the browser to validate it?
This is possible, too. But why on earth would you want to do
this? What if you have a multistage registration form, either for
sign-up or for submitting some content? For long forms it could
be useful to split the form into stages (as eBay might do when
Search WWH ::

Custom Search