HTML and CSS Reference
In-Depth Information
Overriding browser defaults
When we make use of the new HTML5 form control types or the
required attribute, the browser gives us pre-baked validation,
with its own built-in error messages. That's great, but what if you
want to customise these error messages? What if it's speak like
a pirate day? Perhaps I want to change all the validation mes-
sages to speak like a pirate, too.
It's possible, with a bit of JavaScript. It's not possible to set
custom validation messages using content attributes (which are
hard-coded in the markup), but we can add them to the DOM
attributes (which are accessible through JavaScript). So we can
either set these before the validation runs, or when the form is
submitted we can set a custom validation message and, at that
point in execution, dynamically create a validation message that
includes the value causing the error.
So instead of reading:
humptydumpty is not a legal e-mail address
We'll change the validation to read the following in “traditional”
pirate speak:
humptydumpty be not a legal e-mail address
The setCustomValidity method allows me to specify my own
validation message:
var email = document.getElementById('email');
email.form.onsubmit = function () {
email.setCustomValidity(email.value + “ be not a legal
¬ e-mail address”);
Yo u c a in s e e O p e r a r e in d e r i in g t h e c u s t o m v a l i d a t i o in m e s s a g e i in
Figures 3.11 and 3.12 .
Opera is currently the only browser that has support for the
native validation messages, and so there's nothing to bench-
mark against. I say this because you'll notice the custom valida-
tion message is prefi xed with “The value humptydumpty is not
allowed by a script on the page!”. This is still in the browser's
control, and we can do nothing to change this (at time of writ-
ing). So it's something to be wary of if you're going to use cus-
tom validation messages.
Search WWH ::

Custom Search