HTML and CSS Reference
In-Depth Information
telling the browser to run through its checks. If you want to take
control of the presentation of validation feedback, then you
don't want to use this method.
Element validity
Individual form fi elds, along with having the checkValidity
method, also have a validity DOM attribute that returns a
ValidityState object. There's 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 fi elds and check the validity
attribute. But what happens if the fi eld doesn't have any valida-
tion rules? You're in luck: The API provides a willValidate attri-
bute that we can test to see whether we should or shouldn't try
to validate this particular fi eld. 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 .
NOTE It's worth noting
that <fieldset> ele-
ments also have the validity
attribute, but unfortunately they
don't do anything: The valid
attribute is always true. You can
also call the checkValidity
method on fi eldsets, 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 multi-stage 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
you're selling an item). You might even want to allow your visi-
tors to save the state of their submission, even if the form isn't
currently complete and valid.
 
 
Search WWH ::




Custom Search