Меню

форма для номера телефона html

Форма для номера телефона html

Despite the fact that inputs of type tel are functionally identical to standard text inputs, they do serve useful purposes; the most quickly apparent of these is that mobile browsers — especially on mobile phones — may opt to present a custom keypad optimized for entering phone numbers. Using a specific input type for telephone numbers also makes adding custom validation and handling of phone numbers more convenient.

Note: Browsers that don’t support type tel fall back to being a standard text (en-US) input.

Value

The element’s value attribute contains a DOMString that either represents a telephone number or is an empty string ( «» ).

Additional attributes

In addition to the attributes that operate on all elements regardless of their type, telephone number inputs support the following attributes:

Attribute Description
maxlength The maximum length, in UTF-16 characters, to accept as a valid input
minlength The minimum length that is considered valid for the field’s contents
pattern A regular expression the entered value must match to pass constraint validation
placeholder An example value to display inside the field when it has no value
readonly A Boolean attribute which, if present, indicates that the field’s contents should not be user-editable
size The number of characters wide the input field should be onscreen

maxlength

The input will fail constraint validation if the length of the text entered into the field is greater than maxlength UTF-16 code units long.

minlength

The telephone number field will fail constraint validation if the length of the text entered into the field is fewer than minlength UTF-16 code units long.

pattern

See Pattern validation below 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.

Non-standard attributes

The following non-standard attributes are available to telephone number input fields. As a general rule, you should avoid using them unless it can’t be helped.

Attribute Description
autocorrect Whether or not to allow autocorrect while editing this input field. Safari only.
mozactionhint A string indicating the type of action that will be taken when the user presses the Enter or Return key while editing the field; this is used to determine an appropriate label for that key on a virtual keyboard. Firefox for Android only.

Using tel inputs

Telephone numbers are a very commonly collected type of data on the web. When creating any kind of registration or e-commerce site, for example, you will likely need to ask the user for a telephone number, whether for business purposes or for emergency contact purposes. Given how commonly-entered phone numbers are, it’s unfortunate that a «one size fits all» solution for validating phone numbers is not practical.

Fortunately, you can consider the requirements of your own site and implement an appropriate level of validation yourself. See Validation, below, for details.

Custom keyboards

One of the main advantages of is that it causes mobile browsers to display a special keyboard for entering phone numbers. For example, here’s what the keypads look like on a couple of devices.

Examples of custom keyboards on mobile devices.

Firefox for Android WebKit iOS (Safari/Chrome/Firefox)
fx android tel iphone tel keyboard 50pct

A simple tel input

In its most basic form, a tel input can be implemented like this:

Placeholders

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, for instance, the tel edit box is 20 characters wide:

Element value length

The size is separate from the length limitation on the entered telephone number. You can specify a minimum length, in characters, for the entered telephone number using the minlength attribute; similarly, use maxlength to set the maximum length of the entered telephone number.

The example below creates a 20-character wide telephone number entry box, requiring that the contents be no shorter than 9 characters and no longer than 14 characters.

Note: The above attributes do affect Validation — the above example’s inputs will count as invalid if the length of the value is less than 9 characters, or more than 14. Most browser won’t even let you enter a value over the max length.

Providing default options

As always, you can provide a default value for an tel input box by setting its value attribute:

Offering suggested values

With the element and its s in place, the browser will offer the specified values as potential values for the email 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 email addresses. Then, as the user types, the list is adjusted to show only filtered matching values. Each typed character narrows down the list until the user makes a selection or types a custom value.

Here’s a screenshot of what that might look like:

phone number with options

Validation

As we’ve touched on before, it’s quite difficult to provide a one-size-fits-all client-side validation solution for phone numbers. So what can we do? Let’s consider some options.

Important: HTML form validation is not a substitute for server-side scripts that ensure the entered data is in the proper format before it is allowed into the database. It’s far too easy for someone to make adjustments to the HTML that allow them to bypass the validation, or to remove it entirely. It’s also possible for someone to simply 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.

Making telephone numbers required

You can make it so that an empty input is invalid and won’t be submitted to the server using the required attribute. For example, let’s use this HTML:

And let’s include the following CSS to highlight valid entries with a checkmark and invalid entries with a cross:

The output looks like this:

Pattern validation

If you want to further restrict entered numbers so they also have to conform to a specific pattern, you can use the pattern attribute, which takes as its value a regular expression that entered values have to match.

In this example we’ll use the same CSS as before, but our HTML is changed to look like this:

Notice how the entered value is reported as invalid unless the pattern xxx-xxx-xxxx is matched; for instance, 41-323-421 won’t be accepted. Neither will 800-MDN-ROCKS. However, 865-555-6502 will be accepted. This particular pattern is obviously only useful for certain locales — in a real application you’d probably have to vary the pattern used depending on the locale of the user.

Examples

In this example, we present a simple interface with a element that lets the user choose which country they’re in, and a set of elements to let them enter each part of their phone number; there is no reason why you can’t have multiple tel inputs.

Each input has a placeholder attribute to show a hint to sighted users about what to enter into it, a pattern to enforce a specific number of characters for the desired section, and an aria-label attribute to contain a hint to be read out to screenreader users about what to enter into it.

The example looks like this:

This is an interesting idea, which goes to show a potential solution to the problem of dealing with international phone numbers. You would have to extend the example of course to provide the correct pattern for potentially every country, which would be a lot of work, and there would still be no foolproof guarantee that the users would enter their numbers correctly.

It makes you wonder if it is worth going to all this trouble on the client-side, when you could just let the user enter their number in whatever format they wanted on the client-side and then validate and sanitize it on the server. But this choice is yours to make.

Источник

Форма для номера телефона html

За установку цвета в HTML5 отвечает специальный элемент input с типом color :

Элемент отображает выбранный цвет. А при нажатии на него появляется специальное диалоговое окно для установки цвета:

2.36

Значением этого элемента будет числовой шестнадцатеричный код выбранного цвета.

С помощью элемента datalist мы можем задать набор цветов, из который пользователь может выбрать нужный:

2.37

Поля для ввода url, email, телефона

Для их настройки мы можем использовать те же атрибуты, что и для обычного текстового поля:

maxlength : максимально допустимое количество символов в поле

pattern : определяет шаблон, которому должен соответствовать вводимый текст

placeholder : устанавливает текст, который по умолчанию отображается в поле

readonly : делает текстовом поле доступным только для чтения

required : указывает, что текстовое поле обязательно должно иметь значение

size : устанавливает ширину поля в видимых символах

value : устанавливает значение по умолчанию для поля

list : устанавливает привязку к элементу datalist со списком возможных значений

2.17

Основное преимущество подобных полей ввода перед обычными текстовыми полями состоит в том, что поля ввода для email, url, телефона для проверки ввода используют соответствующий шаблон. Например, если мы введем в какое-либо поле некорректное значение и попробуем отправить форму, то браузер может отобразить нам сообщение о некорректном вводе, а форма не будет отправлена:

Источник

Как сделать ссылку на номер телефона в HTML: протокол tel:, оформление и советы

telephone1Недавно читал, что объемы мирового мобильного трафика уже превышают десктопных пользователей. В данном блоге этого пока не случилось, но в интернет-магазине одного из моих клиентов бОльшая часть людей заходит именно через планшеты/смартфоны. Поэтому меня попросили сделать продвинутую ссылку на телефон на сайте, которая при нажатии автоматически бы открывала соответствующее приложение с набором номера.

Некоторые устройства без проблем понимают написанные телефоны, например, слышал, что в Android для этого достаточно заключить линк в span:

При клике по тексту, в теории, весь номер должен выделиться, но на практике у меня это почему-то не получилось.

Лучше использовать в ссылке tel параметр:

Фишка работает с 2011 года, хотя не все браузеры одинаково с ней дружат(жили) — как это часто бывает в верстке, есть определенные нюансы. Поэтому я решил опубликовать немного инфы по теме из интересной англоязычной статьи.

Спецификация и поддержка

По факту tel: — это не опция «А» тега, а протокол (такой же как http: или mailto:, отвечающие за линки на веб-страницы и почтовые адреса соответственно). Конкретного и детального его описания в HMTL5, вроде бы, нет, но после принятия данного стандарта в iOS, он стал использоваться повсеместно.

Даже без спецификации многие браузеры вполне адекватно понимают ссылку на телефон в HTML, однако процесс обработки клика встречается разный: начиная от открытия диалогового окна с выбором приложения и заканчивая банальным игнорированием.

Как реагируют типовые программы:

    telephone3

Увы, не все разработчики браузеров для компьютеров (в том числе и непопулярных) позаботились о должной поддержке tel протокола, вероятно, работа над этим будет продолжаться. Хотя без конкретной спецификации она выглядит несколько абстрактной.

Оформление ссылки tel: в HTML

Поскольку линк находится в теге А, то отображение ссылки номера телефона полностью зависит от его стилей. Например, если для А добавили класс phone-style, то будет:

Убираем подчеркивание с text-decoration чтобы элемент выглядел как текст.

Если хотите применить один и тот же стиль всем телефонам на сайте, то пишете:

С помощью псевдо класса before и представления символов в unicode можно добавить небольшую иконку в начале:

Советы по созданию ссылки на номер телефона

Данная фишка для мобильных устройств — громадное преимущество, т.к. является отличным Call To Action маркетинговым инструментом. Посетителю сайта не надо пытаться выделить весь текст, вводить номер по памяти и т.п., он просто кликает в нужном месте, и активная ссылка телефона сделает свое дело. Однако тут есть нюансы.

Определение мобильных устройств

Как я уже сказал выше, в декстопнах подобный линк срабатывает далеко не всегда, поэтому разумно использовать разный код под разные типы устройств. Чтобы опция функционировала только в мобильных браузерах добавляете в шаблон, например, следующий JavaScript:

Здесь, в зависимости от результата условия в IF, в блоке с создается либо ссылка на телефон с tel:, либо просто HTML текст.

SEO оптимизация

В оригинальной статье есть пример кода контактов для бизнес сайтов, где информация может быть использована в Google выдаче.

telephone2

Beach Bunny Swimwear

Теоретически, в линке можно еще указать rel=»nofollow».

Убираем автоопределение

Если вы собираетесь внедрять сегодняшний урок в свой шаблон, то вероятнее всего захотите отключить автоопределение телефона в iOS. Как минимум, чтобы система не переопределила существующие стили. Для этого в HEAD дописываете строку:

Итого. Если вы размещаете контактную информацию на сайте, то по умолчанию ссылки на телефоны не открываются — вам нужно использовать специальный протокол tel: в HTML теге А. Опция не имеет четкой спецификации, и поддерживается браузерами слегка «хаотично» — учитывайте это. В заключительной части я указал 3 пожелания, которые было бы неплохо внести в ваш код: отключить линки на дестопах, отформатировать код для лучшего считывания поисковыми роботами и т.п.

Если будут вопросы, пишите их ниже. А вы добавляете в своих проектах активные ссылки на номера телефонов? Почему да / нет?

Источник

Форма для номера телефона html

Despite the fact that inputs of type tel are functionally identical to standard text inputs, they do serve useful purposes; the most quickly apparent of these is that mobile browsers — especially on mobile phones — may opt to present a custom keypad optimized for entering phone numbers. Using a specific input type for telephone numbers also makes adding custom validation and handling of phone numbers more convenient.

Note: Browsers that don’t support type tel fall back to being a standard text input.

Value

The element’s value attribute contains a DOMString that either represents a telephone number or is an empty string ( «» ).

Additional attributes

In addition to the attributes that operate on all elements regardless of their type, telephone number 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 input will fail constraint validation if the length of the text entered into the field is greater than maxlength UTF-16 code units long.

minlength

The telephone number field will fail constraint validation if the length of the text entered into the field is fewer than minlength UTF-16 code units long.

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 Pattern validation below 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.

Non-standard attributes

The following non-standard attributes are available to telephone number input fields. As a general rule, you should avoid using them unless it can’t be helped.

autocorrect

A Safari extension, the autocorrect attribute is a string which indicates whether or not to activate automatic correction while the user is editing this field. Permitted values are:

Enable automatic correction of typos, as well as processing of text substitutions if any are configured.

Disable automatic correction and text substitutions.

mozactionhint

A Mozilla extension, supported by Firefox for Android, which provides a hint as to what sort of action will be taken if the user presses the Enter or Return key while editing the field. This information is used to decide what kind of label to use on the Enter key on the virtual keyboard.

Using tel inputs

Telephone numbers are a very commonly collected type of data on the web. When creating any kind of registration or e-commerce site, for example, you will likely need to ask the user for a telephone number, whether for business purposes or for emergency contact purposes. Given how commonly-entered phone numbers are, it’s unfortunate that a «one size fits all» solution for validating phone numbers is not practical.

Fortunately, you can consider the requirements of your own site and implement an appropriate level of validation yourself. See Validation, below, for details.

Custom keyboards

One of the main advantages of is that it causes mobile browsers to display a special keyboard for entering phone numbers. For example, here’s what the keypads look like on a couple of devices.

Firefox for Android WebKit iOS (Safari/Chrome/Firefox)
fx android tel iphone tel keyboard 50pct

A simple tel input

In its most basic form, a tel input can be implemented like this:

Placeholders

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, for instance, the tel edit box is 20 characters wide:

Element value length

The size is separate from the length limitation on the entered telephone number. You can specify a minimum length, in characters, for the entered telephone number using the minlength attribute; similarly, use maxlength to set the maximum length of the entered telephone number.

The example below creates a 20-character wide telephone number entry box, requiring that the contents be no shorter than 9 characters and no longer than 14 characters.

Note: The above attributes do affect Validation — the above example’s inputs will count as invalid if the length of the value is less than 9 characters, or more than 14. Most browser won’t even let you enter a value over the max length.

Providing default options

Providing a single default using the value attribute

As always, you can provide a default value for an tel input box by setting its value attribute:

Offering suggested values

With the element and its s in place, the browser will offer the specified values as potential values for the email 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 email addresses. Then, as the user types, the list is adjusted to show only filtered matching values. Each typed character narrows down the list until the user makes a selection or types a custom value.

Here’s a screenshot of what that might look like:

phone number with options

Validation

As we’ve touched on before, it’s quite difficult to provide a one-size-fits-all client-side validation solution for phone numbers. So what can we do? Let’s consider some options.

Warning: HTML form validation is not a substitute for server-side scripts that ensure the entered data is in the proper format before it is allowed into the database. It’s far too easy for someone to make adjustments to the HTML that allow them to bypass the validation, or to remove it entirely. 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.

Making telephone numbers required

You can make it so that an empty input is invalid and won’t be submitted to the server using the required attribute. For example, let’s use this HTML:

And let’s include the following CSS to highlight valid entries with a checkmark and invalid entries with a cross:

The output looks like this:

Pattern validation

If you want to further restrict entered numbers so they also have to conform to a specific pattern, you can use the pattern attribute, which takes as its value a regular expression that entered values have to match.

In this example we’ll use the same CSS as before, but our HTML is changed to look like this:

Notice how the entered value is reported as invalid unless the pattern xxx-xxx-xxxx is matched; for instance, 41-323-421 won’t be accepted. Neither will 800-MDN-ROCKS. However, 865-555-6502 will be accepted. This particular pattern is obviously only useful for certain locales — in a real application you’d probably have to vary the pattern used depending on the locale of the user.

Examples

In this example, we present a simple interface with a element that lets the user choose which country they’re in, and a set of elements to let them enter each part of their phone number; there is no reason why you can’t have multiple tel inputs.

Each input has a placeholder attribute to show a hint to sighted users about what to enter into it, a pattern to enforce a specific number of characters for the desired section, and an aria-label attribute to contain a hint to be read out to screenreader users about what to enter into it.

The example looks like this:

This is an interesting idea, which goes to show a potential solution to the problem of dealing with international phone numbers. You would have to extend the example of course to provide the correct pattern for potentially every country, which would be a lot of work, and there would still be no foolproof guarantee that the users would enter their numbers correctly.

It makes you wonder if it is worth going to all this trouble on the client-side, when you could just let the user enter their number in whatever format they wanted on the client-side and then validate and sanitize it on the server. But this choice is yours to make.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *