- Validating email addresses
- Using patterns to validate email addresses
- Type=»email» or pattern?
- What you have learned
- Валидация HTML5-форм
- Обязательные поля
- Валидация данных
- Валидация email, URL и номеров
- Использование CSS для подсветки обязательных полей и неверно введенных данных
- Отключение встроенной в браузер валидации
- Кроссбраузерность
- Заключение
Validating email addresses
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 an email address. Does this means that the user cannot type in a fake email 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 an email 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 email 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 email 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 email addresses is which pattern to use. The following HTML5 email 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 email address such as janedoe@unknown.com
Type=»email» or pattern?
As both ways of validating email addresses has 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 email addresses is to set the type attribute to email, type=»email»
- Not all browsers look for the same pattern when validating email addresses
- You can also use the pattern attribute to validate email 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
Is your preferred language not on the list? Click here to help us translate this article into your language!
Валидация HTML5-форм
Несколько месяцев назад, Sandeep представил на всеобщее обозрение HTML Constraint API , показав, как можно использовать новые HTML5-элементы ввода и их атрибуты для валидации форм с минимальным использованием JavaScript.
В этой статье, я собираюсь разобрать валидацию на примере простой формы заказа, используя Constraint API, сделав акцент на том, чтобы не снизить удобства использования.
На всякий случай напомню, если вы не читали статью Sandeep о нововведениях в HTML5 относительно новых типов элементов ввода и атрибутов тега , которые позволяют браузерам самостоятельно производить валидацию на клиентской стороне без необходимости использования JavaScript. Чтобы начать использование новых возможностей, вам нужно просто добавить новые атрибуты и типы элементов ввода к тегу .
Строго говоря, вам следует использовать HTML5 DOCTYPE, иначе HTML-валидатор выдаст ошибки на странице. Но хорошая новость состоит в том, что новые функции имеют обратную совместимость. Если, к примеру, какой-нибудь старый браузер их не поддерживает, то это не « сломает » всю HTML-страницу – неподдерживаемые элементы будут отображены как .
Несмотря на то, что использование валидации форм на стороне клиента очень удобно и позволяет быстро оповестить пользователя об ошибках во введенных данных без необходимости обращения к серверу, это не отменяет необходимости проверять данные перед их отправкой.
Давайте разберем пример, чтобы понять, как можно проводить валидацию, используя лишь встроенные средства браузера. Ниже приведен код простой формы заказа: