HTML5 Guidelines for Web Developers

(coco) #1

62 Chapter 3—Intelligent Forms


ensures that the browser will check for a valid e-mail address. Additionally, we
want to specifically exclude three e-mail domains:

var invalidMailDomains = [
'hotmail.com', 'gmx.com', 'gmail.com' ];

function checkMailDomain(item) {
for (var i=0; i<invalidMailDomains.length; i++) {
if (item.value.match(invalidMailDomains[i]+'$')) {
item.setCustomValidity('E-mail addresses from '
+invalidMailDomains[i]+' are not accepted.');
} else {
item.setCustomValidity('');
}
item.checkValidity();
}
}

Each element in the array invalidMailDomains is compared to the value of the input
element. The JavaScript function match() works with regular expressions, which is
why we add a $symbol to the domain name, to indicate the end of the character
string. If the character strings match, the setCustomValidity function is called and
displays the appropriate error message. If it is not a domain name from the array,
setCustomValidity() is called with an empty character string. Internally, this at-
taches the variable validationMessage to the input element, which Opera then dis-
plays (see Figure 3.15). The concluding call of the checkValidity function triggers
the validity check and leads to the aforementioned error message.

Figure 3.15 Opera displays an error message during manual error handling (checking e-mail
domain)
Free download pdf