One of the new values to the type attribute is email. Using this type of field instead of the regular text field the browser uses a regular expression to check that the user has in fact typed in a mail address. Does this means that the user cannot type in a fake e-mail address? No. But you do not have to worry that the user types in a comma instead of a period or that she accidentally types a space. No matter what the user is going to submit, it is going to look like a mail address. Here is how it looks:
Some browsers only look for the @ and other browsers look for at pattern consisting of a @ followed by at least one letter and a dot.
As of right now, this is not supported by e.g. Internet Explorer 9.0 and previous version or by the Android browser. This means that in order to have valid mail validation for these browsers you will have to make a work-around to have this feature working in all browsers. This does not mean that you should not implement the attribute email, because if the browser does not regocnize type=”email” it will just treat is as type=”text” and render it as plain text.
Using patterns to validate email addresses
Another way to validate addresses is to use the pattern attribute. As mentioned in the chapter about patterns, the pattern can be anything you specify and it is based on regular expressions. I will not go further into the subject of regular expressions as this is a very comprehensive subject.
All you need to know to use patterns to validate addresses is which pattern to use. The following HTML5 address regular expression is close to a complete example of what your pattern could look like. (Thanks to Gervase Markham). Here is what the pattern looks like:
As you can see the pattern is pretty intricate, but basically it checks whether or not the user input looks like a normal address such as [email protected]
Type=”email” or pattern?
As both ways of validating addresses have their pros and cons it is up to you to decide which one to use. You should not try to use them both at the same time as this might induce a clash in browsers that support both features. Using type=”email” has the advantage that it is semantically correct both using the pattern attribute has the advantage that there are several easy-to-use polyfills on the web which ensures support for a greater range of audience.
What you have learned
- Using HTML5 the semantically correct way of validating addresses is to set the type attribute to mail, type=”email”
- Not all browsers look for the same pattern when validating addresses
- You can also use the pattern attribute to validate addresses
- The type=”email” ensures semantically correct HTML5 where as the pattern attribute might ensure a valid email address more frequently
- The pattern attribute can be supported using a polyfill