- Адрес электронной почты
- Форум
- Справочник
- Type email не работает
- Value
- Additional attributes
- maxlength
- minlength
- multiple
- pattern
- placeholder
- readonly
- Using email inputs
- A simple email input
- Allowing multiple e-mail addresses
- Placeholders
- Controlling the input size
- Physical input element size
- Element value length
- Providing default options
- Providing a single default using the value attribute
- Offering suggested values
- Validation
- Basic validation
- Pattern validation
Адрес электронной почты
В формах часто требуется ввод адреса электронной почты, для чего обычно применяется однострочное текстовое поле. Однако в отличие от него специальное поле для ввода адреса почты позволяет проверять корректность записи введённого адреса.
Синтаксис создания поля следующий.
Атрибуты по большей части совпадают с текстовым полем и приведены в табл. 1.
Табл. 1. Атрибуты поля для почтового адреса
| Атрибут | Описание |
|---|---|
| maxlength | Устанавливает максимальное число символов, которое может быть введено пользователем в поле. Когда это количество достигается при наборе, дальнейший ввод становится невозможным. Если этот атрибут опустить, то можно вводить строку длинее самого поля. |
| multiple | Позволяет указывать несколько адресов через запятую. |
| name | Имя поля, предназначено для того, чтобы обработчик формы мог его идентифицировать. |
| size | Ширина поля, которая определяется числом символов моноширинного шрифта. Иными словами, ширина задается количеством близстоящих букв одинаковой ширины по горизонтали. |
| value | Начальный почтовый адрес отображаемый в поле. |
По сравнению со значением text , добавлен атрибут multiple , который позволяет вводить сразу несколько почтовых адресов.
В примере 1 показано применение значения email для создания формы авторизации на сайте, где в качестве логина указывается адрес электронной почты.
Пример 1. Адрес электронной почты
HTML5 IE 10+ Cr Op Sa Fx
По своему виду поле для ввода адреса ничем не отличается от текстового поля. Различия проявляются, если указать некорректный адрес, в этом случае браузер выведет замечание об ошибке. Firefox поле с неверным адресом обозначает красной рамкой и сообщением об ошибке при отправке формы (рис. 1), Chrome никак сразу не выделяет поле с ошибкой, но выводит сообщение при отправке формы (рис. 2). Аналогично поступает и Opera (рис. 3). Сама форма на сервер не отправляется, пока ошибка не будет исправлена.
Рис. 1. Отправка формы в Firefox
Рис. 2. Отправка формы в Chrome
Рис. 3. Отправка формы в Opera
Другие популярные браузеры (IE, Safari) интерпретируют поле для адреса электронной почты как текстовое.
Источник
Форум
Справочник
| Опции темы | Искать в теме |
Где то здесь ошибка в регулярке, но где не могу понять.
Цель: при вводе емайла в текстовом поле чтобы сразу проверялось на валидность то что вводится и отсекались бы невалидные символы.
С полем логина или пароля у меня все без проблем работает, там регулярка простая. А вот тут затык.
Мне кажется, либо я неточно выразился в первом посте, либо Вы меня не так поняли.
Вот пример того что работает. Отсечение невалидных символов в поле логина:
Теперь хочу сделать то же но с полем Email. Вот что у меня получилось:
Но это не правильный подход. Ибо теперь можно вводить такие email как:
@@asdasd.
asdasd. @
asdasd@@asdasd.ru
asdasd@asdasd. ru
asdasdas@asdasd@.rrrrrrr
и др.
Полезный пример. Но у меня задача найти правильную регулярку для моего случая. У меня есть готовая функция (см выше), надо лишь правильно запихнуть туда регулярку. Пробовал взять регулярку из Вашего последнего примера — не получилось.
Моя функция позволяет на лету удалять из текстового поля символы которые не являются валидными. Не могу лишь регулярку правильную для емайла подобрать.
Источник
Type email не работает
elements of type email are used to let the user enter and edit an e-mail address, or, if the multiple attribute is specified, a list of e-mail addresses.
The input value is automatically validated to ensure that it’s either empty or a properly-formatted e-mail address (or list of addresses) before the form can be submitted. The :valid and :invalid CSS pseudo-classes are automatically applied as appropriate to visually denote whether the current value of the field is a valid e-mail address or not.
On browsers that don’t support inputs of type email , a email input falls back to being a standard text input.
| Value | A DOMString representing an e-mail address, or empty |
| Events | change and input |
| Supported Common Attributes | autocomplete , list , maxlength , minlength , multiple , name , pattern , placeholder , readonly , required , size , and type |
| IDL attributes | list and value |
| Methods | select() |
Value
The element’s value attribute contains a DOMString which is automatically validated as conforming to e-mail syntax. More specifically, there are three possible value formats that will pass validation:
- An empty string («») indicating that the user did not enter a value or that the value was removed.
- A single properly-formed e-mail address. This doesn’t necessarily mean the e-mail address exists, but it is at least formatted correctly. In simple terms, this means username@domain or username@domain.tld . There’s more to it than that, of course; see Validation for a regular expression that matches the e-mail address validation algorithm.
- If and only if the multiple attribute is specified, the value can be a list of properly-formed comma-separated e-mail addresses. Any trailing and leading whitespace is removed from each address in the list.
See Validation for details on how e-mail addresses are validated to ensure that they’re formatted properly.
Additional attributes
In addition to the attributes that operate on all elements regardless of their type, email inputs support the following attributes.
The values of the list attribute is the id of a element located in the same document. The provides a list of predefined values to suggest to the user for this input. Any values in the list that are not compatible with the type are not included in the suggested options. The values provided are suggestions, not requirements: users can select from this predefined list or provide a different value.
maxlength
The maximum number of characters (as UTF-16 code units) the user can enter into the email input. This must be an integer value 0 or higher. If no maxlength is specified, or an invalid value is specified, the email input has no maximum length. This value must also be greater than or equal to the value of minlength .
The input will fail constraint validation if the length of the text value of the field is greater than maxlength UTF-16 code units long. Constraint validation is only applied when the value is changed by the user.
minlength
The minimum number of characters (as UTF-16 code units) the user can enter into the email input. This must be an non-negative integer value smaller than or equal to the value specified by maxlength . If no minlength is specified, or an invalid value is specified, the email input has no minimum length.
The input will fail constraint validation if the length of the text entered into the field is fewer than minlength UTF-16 code units long. Constraint validation is only applied when the value is changed by the user.
multiple
A Boolean attribute which, if present, indicates that the user can enter a list of multiple e-mail addresses, separated by commas and, optionally, whitespace characters. See Allowing multiple e-mail addresses for an example, or HTML attribute: multiple for more details.
Note: Normally, if you specify the required attribute, the user must enter a valid e-mail address for the field to be considered valid. However, if you add the multiple attribute, a list of zero e-mail addresses (an empty string, or one which is entirely whitespace) is a valid value. In other words, the user does not have to enter even one e-mail address when multiple is specified, regardless of the value of required .
pattern
The pattern attribute, when specified, is a regular expression that the input’s value must match in order for the value to pass constraint validation. It must be a valid JavaScript regular expression, as used by the RegExp type, and as documented in our guide on regular expressions; the ‘u’ flag is specified when compiling the regular expression, so that the pattern is treated as a sequence of Unicode code points, instead of as ASCII. No forward slashes should be specified around the pattern text.
If the specified pattern is not specified or is invalid, no regular expression is applied and this attribute is ignored completely.
Note: Use the title attribute to specify text that most browsers will display as a tooltip to explain what the requirements are to match the pattern. You should also include other explanatory text nearby.
See the section Pattern validation for details and an example.
placeholder
The placeholder attribute is a string that provides a brief hint to the user as to what kind of information is expected in the field. It should be a word or short phrase that demonstrates the expected type of data, rather than an explanatory message. The text must not include carriage returns or line feeds.
If the control’s content has one directionality (LTR or RTL) but needs to present the placeholder in the opposite directionality, you can use Unicode bidirectional algorithm formatting characters to override directionality within the placeholder; see Overriding BiDi using Unicode control characters in The Unicode Bidirectional Text Algorithm for those characters.
Note: Avoid using the placeholder attribute if you can. It is not as semantically useful as other ways to explain your form, and can cause unexpected technical issues with your content. See Labels and placeholders in : The Input (Form Input) element for more information.
readonly
A Boolean attribute which, if present, means this field cannot be edited by the user. Its value can, however, still be changed by JavaScript code directly setting the HTMLInputElement value property.
Note: Because a read-only field cannot have a value, required does not have any effect on inputs with the readonly attribute also specified.
The size attribute is a numeric value indicating how many characters wide the input field should be. The value must be a number greater than zero, and the default value is 20. Since character widths vary, this may or may not be exact and should not be relied upon to be so; the resulting input may be narrower or wider than the specified number of characters, depending on the characters and the font ( font settings in use).
This does not set a limit on how many characters the user can enter into the field. It only specifies approximately how many can be seen at a time. To set an upper limit on the length of the input data, use the maxlength attribute.
Using email inputs
E-mail addresses are among the most frequently-inputted textual data forms on the web; they’re used when logging into web sites, when requesting information, to allow order confirmation, for webmail, and so forth. As such, the email input type can make your job as a web developer much easier since it can help simplify your work when building the user interface and logic for e-mail addresses. When you create an email input with the proper type value, email , you get automatic validation that the entered text is at least in the correct form to potentially be a legitimate e-mail address. This can help avoid cases in which the user mistypes their address, or provides an invalid address.
It’s important, however, to note that this is not enough to ensure that the specified text is an e-mail address which actually exists, corresponds to the user of the site, or is acceptable in any other way. It ensures that the value of the field is properly formatted to be an e-mail address.
Note: It’s also crucial to remember that a user can tinker with your HTML behind the scenes, so your site must not use this validation for any security purposes. You must verify the e-mail address on the server side of any transaction in which the provided text may have any security implications of any kind.
A simple email input
Currently, all browsers which implement this element implement it as a standard text input field with basic validation features. The specification does, however, allow browsers latitude on this. For example, the element could be integrated with the user’s device’s built-in address book to allow picking e-mail addresses from that list. In its most basic form, an email input can be implemented like this:
Notice that it’s considered valid when empty and when a single validly-formatted e-mail address is entered, but is otherwise not considered valid. By adding the required attribute, only validly-formed e-mail addresses are allowed; the input is no longer considered valid when empty.
Allowing multiple e-mail addresses
By adding the multiple Boolean attribute, the input can be configured to accept multiple e-mail addresses.
The input is now considered valid when a single e-mail address is entered, or when any number of e-mail addresses separated by commas and, optionally, some number of whitespace characters are present.
Note: When multiple is used, the value is allowed to be empty.
Some examples of valid strings when multiple is specified:
- «»
- «me@example»
- «me@example.org»
- «me@example.org,you@example.org»
- «me@example.org, you@example.org»
- «me@example.org,you@example.org, us@example.org»
Some examples of invalid strings:
Placeholders
Sometimes it’s helpful to offer an in-context hint as to what form the input data should take. This can be especially important if the page design doesn’t offer descriptive labels for each . This is where placeholders come in. A placeholder is a value that demonstrates the form the value should take by presenting an example of a valid value, which is displayed inside the edit box when the element’s value is «». Once data is entered into the box, the placeholder disappears; if the box is emptied, the placeholder reappears.
Here, we have an email input with the placeholder sophie@example.com . Note how the placeholder disappears and reappears as you manipulate the contents of the edit field.
Controlling the input size
You can control not only the physical length of the input box, but also the minimum and maximum lengths allowed for the input text itself.
Physical input element size
The physical size of the input box can be controlled using the size attribute. With it, you can specify the number of characters the input box can display at a time. In this example the email edit box is 15 characters wide:
Element value length
The size is separate from the length limitation on the entered e-mail address itself so that you can have fields fit in a small space while still allowing longer e-mail address strings to be entered. You can specify a minimum length, in characters, for the entered e-mail address using the minlength attribute; similarly, use maxlength to set the maximum length of the entered e-mail address.
The example below creates a 32 character-wide e-mail address entry box, requiring that the contents be no shorter than 3 characters and no longer than 64 characters.
Providing default options
Providing a single default using the value attribute
As always, you can provide a default value for an email input box by setting its value attribute:
Offering suggested values
Taking it a step further, you can provide a list of default options from which the user can select by specifying the list attribute. This doesn’t limit the user to those options, but does allow them to select commonly-used e-mail addresses more quickly. This also offers hints to autocomplete . The list attribute specifies the ID of a , which in turn contains one element per suggested value; each option ‘s value is the corresponding suggested value for the email entry box.
With the element and its s in place, the browser will offer the specified values as potential values for the e-mail address; this is typically presented as a popup or drop-down menu containing the suggestions. While the specific user experience may vary from one browser to another, typically clicking in the edit box presents a drop-down of the suggested e-mail addresses. Then, as the user types, the list is filtered to show only matching values. Each typed character narrows down the list until the user makes a selection or types a custom value.
Validation
There are two levels of content validation available for email inputs. First, there’s the standard level of validation offered to all s, which automatically ensures that the contents meet the requirements to be a valid e-mail address. But there’s also the option to add additional filtering to ensure that your own specialized needs are met, if you have any.
Warning: HTML form validation is not a substitute for scripts that ensure that the entered data is in the proper format.It’s far too easy for someone to make adjustments to the HTML that allow them to bypass the validation, or to remove it completely. It’s also possible for someone to bypass your HTML entirely and submit the data directly to your server. If your server-side code fails to validate the data it receives, disaster could strike when improperly-formatted data (or data which is too large, is of the wrong type, and so forth) is entered into your database.
Basic validation
Browsers that support the email input type automatically provide validation to ensure that only text that matches the standard format for Internet e-mail addresses is entered into the input box. Browsers that implement the specification should be using an algorithm equivalent to the following regular expression:
To learn more about how form validation works and how to take advantage of the :valid and :invalid CSS properties to style the input based on whether or not the current value is valid, see Form data validation.
Note: There are known specification issues related to international domain names and the validation of e-mail addresses in HTML. See W3C bug 15489 for details.
Pattern validation
If you need the entered e-mail address to be restricted further than just «any string that looks like an e-mail address,» you can use the pattern attribute to specify a regular expression the value must match for it to be valid. If the multiple attribute is specified, each individual item in the comma-delineated list of values must match the regular expression.
For example, let’s say you’re building a page for employees of Best Startup Ever, Inc. which will let them contact their IT department for help. In our simplified form, the user needs to enter their e-mail address and a message describing the problem they need help with. We want to ensure that not only does the user provide a valid e-mail address, but for security purposes, we require that the address be an internal corporate e-mail address.
Since inputs of type email validate against both the standard e-mail address validation and the specified pattern , you can implement this easily. Let’s see how:
Источник