HTML and CSS Reference
In-Depth Information
Figure 3.13 shows a custom validation message.
FIguRE 3.13 Opera rendering
the default validation message
for email (left) and our custom
“speak like an angry pirate day”
validation (right).
Unfortunately, as it stands today, only Opera supports this prop-
erly. In fact, it's questionable that the submit event should even
fire if the field is invalid. Perhaps we should be listening for the
invalid event on the element? But if we set the custom valid
message, when the error is corrected, the field remains marked
as invalid because we've set our custom error. So it runs the
invalid test again, removing the custom error—but at this point
the user has to hit submit twice just to get the form to be sub-
mitted when there was a corrected error.
In fact, the only appropriate way of setting a custom message is,
on every key press to check the validity of the field. Personally, I
find this odd that we would have to poll the input element, but in
a way, it behaves the same way the :invalid CSS pseudo selec-
tor works. So our example from above changes to:
<!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.oninput = 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