HTML and CSS Reference
In-Depth Information
Overriding browser defaults
Built-in validation messages are great, but what if you want to
customise these error messages? What if it's Talk Like a Pirate
Day? Perhaps I want to change all the validation messages to
speak like an angry pirate, too.
It's possible, with a bit of JavaScript via setCustomValidity .
However, by setting a custom message, it causes the field to
be invalid in the first place, so the workaround is to first set the
custom validity to an empty string—clearing any custom error—
perform a validity check manually in the code, and then set the
custom message so that it's then presented to the user.
So instead of reading:
humptydumpty is not a legal email address
We'll change the validation to read the following in “traditional”
pirate speak:
humptydumpty be not a legal email address
The setCustomValidity method allows me to specify my own
validation message:
<!DOCTYPE html>
<title>custom validity</title>
<form>
<input type=email id=foo name=foo>
<input type=submit>
</form>
<script>
var email = document.getElementById('foo');
email.form.onsubmit = function () {
// reset any previously specified custom validity - let
¬ the browser run its validation logic
email.setCustomValidity('');
// now, after the browser tested if the value entered is
¬ actually an email address, inject custom validation
¬ message if the validation turns out false (i.e. it's
¬ not an email address)
if (!email.validity.valid) {
email.setCustomValidity(email.value + “ be not a legal
¬ email address”);
}
};
</script>
 
 
Search WWH ::




Custom Search