Как сделать ввод номера телефона html
Перейти к содержимому

Как сделать ввод номера телефона html

  • автор:

HTML input type=”tel” | Explained

Web developers utilize the HTML “input” element with the type “tel” to create the input field for telephone numbers. This type of input field can be utilized by the users for submitting a phone number. Moreover, creating an input field for specifically entering the phone number can make your web page look professional and different from the competitors.

This article will explain the HTML input type=“tel” element.

How to Create an HTML input type=“tel” Element?

To create an HTML input type tel, follow the given steps.

Step 1: Create Input Field for Phone Number

In the HTML file, first, create a div element with the name “main”. Inside this div element, add <form> and <label> elements. Within the label element, first, mention the caption and then add an input tag associated with type and name attributes. After that, include a <button> tag with the caption “Submit”:

Save the file and open it in your browser. At this moment, the web page will look like this:

Step 2: Apply Styles to Input field

Let’s apply styles to the input type tel with CSS properties.

Style “main” div

The “.main” is utilized to access the div element with class main, and the properties that are applied to it are described below:

  • background-color” property is utilized for the setting of the element’s background color.
  • max-width” property is utilized for the setting of the element’s maximum width.
  • margin” property with the value “15px” represents the space of 15px at the top-bottom, and the “auto” generates the equal space on the left-right side of the element.
  • height” property is utilized to set the element’s height to 200px.
  • border-radius” property is utilized for the setting of the element’s width to 30px.

Style “form-main” div

The “.form-main” is utilized to access the div element with the class form-main. The description of the properties applied is mentioned below:

  • display” property with the value set as the “flex” will create a flexible layout for the elements.
  • justify-content” property is utilized to align the flexible items horizontally.
  • align-items” property is utilized to align the flexible items vertically.
  • height” property is utilized for the setting of the element’s height.
  • font-size” property is utilized for the setting of the element’s font size.

Style “input” of form-main div

The form-main class is applied with CSS properties that are explained below:

  • border” property is applied with the value “1px solid rgb(47, 63, 63)”, where 1px represents the width of the border, solid line type, and rgb(47, 63, 63) represents the color.
  • padding” property is assigned with the value “10px”, where the first 10px represents the space on the top and bottom of the content, and the second refers to the 10px space on the left and right side of the element’s content.
  • font-size” property is utilized to set the font size.
  • background-color” property is utilized for the setting of the element’s background color.
  • color” property is utilized to set the font color.
  • outline” property with the value none will remove the outline of the input field when selected.

Style “placeholder” of input

We have only applied color to the input placeholder.

Style the “button” of the form-main

Here is the description of the given properties:

  • border” property is applied with the value “1px solid rgb(47, 63, 63)”, where 1px represents the width of the border, solid line type, and rgb(47, 63, 63) represents the color.
  • padding” property is assigned with the value “10px”, where 10px represents the space on the top and bottom of the content and 10px space on the left and right side of the content.
  • font-size” property is utilized to set the font size.
  • background-color” property is utilized for the setting of the element’s background color.
  • color” property is utilized to set the font color.
  • cursor” with the value set as the “pointer” will change the cursor to a pointing hand when placed on the button.
  • margin-left” property will set a space of 5px to the element’s left.
  • transition” property with the value set as all 0.3s ease allows the element to be moved gradually.

Style the “button” on the hover

By providing the above-mentioned code, the output screen will generate the result as shown below:

Step 3: Add “required” Attribute to Input Field

It is often mandatory to add a specified pattern of the telephone number in our forms, which can be validated before form submission.

To do so, the “required” attribute is utilized in such a way that if a user submits an empty input field, a message will be generated to fill the field as follows:

It can be seen from the below image that entering the value in the input field is mandatory:

Step 4: Add “pattern” Attribute to Input Field

As we know, there is no validation procedure for telephone numbers as they vary from place to place. The pattern attribute is utilized for the specification of the telephone number’s format. As a result, the user can only add a telephone number according to the pattern:

Let’s provide a wrong pattern and see what happens:

It can be observed that the input field notifies the user to enter a number that should match the pattern.

So, let’s enter a telephone number with the correct pattern, click on the “Submit” button and see what happens:

Cool! We have successfully learned how to use an input element of type tel.

Conclusion

To make a phone number field, the HTML input type tel can be utilized. This type can have several attributes to add additional functionalities such as placeholder, pattern, required, and more. More specifically, the pattern attribute is used for setting the pattern for the phone number, and the required attributes restrict the user to submit a non-empty value. This article has demonstrated the HTML input type tel and its attributes with examples.

About the author

Sharqa Hameed

I am a Linux enthusiast, I love to read Every Linux blog on the internet. I hold masters degree in computer science and am passionate about learning and teaching.

<input type="tel">

<input> элемент типа tel используется чтобы разрешить пользователю вводить и редактировать номер телефона. В отличии от <input type=»email»> и <input type=»url»> , введённое значение не проверяется автоматически по определённом формату, перед тем как форма может быть отправлена , потому что форматы телефонных номеров сильно различаются по всему миру

Интерактивный пример

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.

Примечание: Browsers that don’t support type tel fall back to being a standard text (en-US) input.

Value A DOMString representing a telephone number, or empty
Events change (en-US) and input (en-US)
Supported Common Attributes autocomplete , list , maxlength , minlength , pattern , placeholder , readonly , and size
IDL attributes list , selectionStart , selectionEnd , selectionDirection , and value
Methods select() (en-US), setRangeText() (en-US), setSelectionRange()

Value

The <input> 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 <input> 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 maximum number of characters (as UTF-16 code units) the user can enter into the telephone number field. This must be an integer value 0 or higher. If no maxlength is specified, or an invalid value is specified, the telephone number field has no maximum length. This value must also be greater than or equal to the value of minlength .

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

minlength

The minimum number of characters (as UTF-16 code units) the user can enter into the telephone number field. 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 telephone number input has no minimum length.

The telephone number field will fail constraint validation (en-US) 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 How to use Unicode controls for bidi text for more information.

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 <input> accessibility concerns 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.

autocorrect Non-standard

mozactionhint Non-standard

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 <input type=»tel»> 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)
Firefox for Android screen shot Firefox for iOS screenshot

A simple tel input

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

There is nothing magical going on here. When submitted to the server, the above input’s data would be represented as, for example, telNo=+12125553151 .

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 <input> . 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 tel input with the placeholder 123-4567-8901 . 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, 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.

Примечание: 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

Taking it a step farther, you can provide a list of default phone number values from which the user can select. To do this, use the list attribute. This doesn’t limit the user to those options, but does allow them to select commonly-used telephone numbers more quickly. This also offers hints to autocomplete . The list attribute specifies the ID of a <datalist> element, which in turn contains one <option> element per suggested value; each option ‘s value is the corresponding suggested value for the telephone number entry box.

With the <datalist> element and its <option> 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:

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 <select> element that lets the user choose which country they’re in, and a set of <input type=»tel»> 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 JavaScript is relatively simple — it contains an onchange event handler that, when the <select> value is changed, updates the <input> element’s pattern , placeholder , and aria-label to suit the format of telephone numbers in that country/territory.

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

In this article, we will learn how to insert the telephone number of the user into an HTML Form. We know that phone numbers have so many advantages A Telephone number field is the important component of the form. in case of contact directly with the user. A user can also get various messages or notifications regarding the services of the form.

Approach: Here is the basic simple approach to complete the task. Steps are given below

<input type=»tel»>

<input> Элементы <input> типа tel позволяют пользователю вводить и редактировать телефонный номер. В отличие от <input type=»email»> и <input type=»url»> , входное значение не проверяется автоматически на определенный формат перед отправкой формы, потому что форматы телефонных номеров сильно различаются по всему миру.

Try it

Несмотря на то, что вводы типа tel функционально идентичны стандартным text вводам, они служат полезным целям; наиболее очевидным из них является то, что мобильные браузеры — особенно на мобильных телефонах — могут отображать настраиваемую клавиатуру, оптимизированную для ввода телефонных номеров. Использование определенного типа ввода для телефонных номеров также делает добавление пользовательской проверки и обработки телефонных номеров более удобными.

Примечание. Браузеры, не поддерживающие тип tel , возвращаются к стандартному вводу текста .

Value

Атрибут value элемента <input> содержит строку, которая либо представляет номер телефона, либо является пустой строкой ( «» ). value «»

Additional attributes

В дополнение к атрибутам, которые работают со всеми элементами <input> независимо от их типа, входы телефонных номеров поддерживают следующие атрибуты.

Значения атрибута list — это id элемента <datalist> , находящегося в том же документе. <datalist> предоставляет список предопределенных значений предложить пользователю для этого входа. Любые значения в списке, несовместимые с type , не включаются в предлагаемые параметры. Предоставленные значения являются предложениями, а не требованиями: пользователи могут выбрать из этого предопределенного списка или указать другое значение.

maxlength

Максимальное количество символов (в единицах кода UTF-16), которое пользователь может ввести в поле телефонного номера. Это должно быть целочисленное значение 0 или больше. Если ни maxlength не указано, или указано недопустимое значение, то поле номер телефона не имеет максимальную длину. Это значение также должно быть больше или равно значению minlength .

Входные данные не пройдут проверку ограничения, если длина текста, введенного в поле, превышает maxlength кодовых единиц UTF-16.

minlength

Минимальное количество символов (в единицах кода UTF-16), которое пользователь может ввести в поле телефонного номера. Это должно быть неотрицательное целое число, меньшее или равное значению, заданному параметром maxlength . Если ни minlength не указано, или указано недопустимое значение, ввод номера телефона не имеет минимальную длину.

Поле телефонного номера не пройдет проверку ограничения, если длина текста, введенного в поле, меньше minlength кодовых единиц UTF-16.

pattern

pattern атрибут, если указана, является регулярным выражением , что входное в value должно совпадать для того , чтобы передавать значение ограничения проверки . Это должно быть допустимое регулярное выражение JavaScript, используемое типом RegExp и описанное в нашем руководстве по регулярным выражениям ; ‘u’ флаг задан при компиляции регулярного выражения, так что рисунок рассматривается как последовательность кодовых точек Unicode, а не как ASCII. Вокруг текста шаблона не следует указывать косую черту.

Если указанный шаблон не указан или является недействительным,регулярное выражение не применяется и данный атрибут игнорируется полностью.

Примечание. Используйте атрибут title , чтобы указать текст, который большинство браузеров будет отображать в виде всплывающей подсказки, чтобы объяснить, какие требования предъявляются к шаблону. Вы также должны включить рядом другой пояснительный текст.

Подробности и пример см. в разделе Проверка шаблона ниже.

placeholder

placeholder атрибут является строкой , которая предоставляет краткую подсказку пользователю относительно того , какой информации , как ожидается , в этой области. Это должно быть слово или короткая фраза, демонстрирующая ожидаемый тип данных, а не пояснительное сообщение. Текст не должен включать символы возврата каретки или перевода строки.

Если содержимое элемента управления имеет одно направление ( LTR или RTL ), но необходимо представить заполнитель в противоположном направлении, вы можете использовать символы форматирования двунаправленного алгоритма Unicode, чтобы переопределить направление внутри заполнителя; Дополнительные сведения см. в разделе Как использовать элементы управления Unicode для двунаправленного текста .

Примечание. По возможности избегайте использования атрибута placeholder . Это не так семантически полезно, как другие способы объяснения вашей формы, и может вызвать неожиданные технические проблемы с вашим контентом. Для получения дополнительной информации см. Ярлыки и заполнители в элементе <input>: The Input (Form Input) .

readonly

Логический атрибут, который, если он присутствует, означает, что это поле не может редактироваться пользователем. Однако его value может быть изменено кодом JavaScript, напрямую устанавливающим HTMLInputElement value HTMLInputElement .

Примечание. Поскольку поле, доступное только для чтения, не может иметь значения, required не влияет на входные данные, для которых также указан атрибут readonly .

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

Это не устанавливает ограничения на количество символов, которые пользователь может ввести в поле. Он лишь указывает приблизительно, сколько можно увидеть одновременно. Чтобы установить верхний предел длины входных данных, используйте атрибут maxlength .

Non-standard attributes

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

autocorrect

В расширении Safari атрибут autocorrect представляет собой строку, которая указывает, следует ли активировать автоматическое исправление, когда пользователь редактирует это поле. Допустимые значения:

Включает автоматическую коррекцию опечаток,а также обработку подстановок текста,если они настроены.

Отключить автоматическое исправление и замену текста.

mozactionhint

Расширение Mozilla,которое дает подсказку о том,какое действие будет предпринято,если пользователь нажмет кнопку Enter or Return во время редактирования поля.

Этот атрибут устарел: вместо него используйте глобальный атрибут enterkeyhint .

Использование тел-входов

Телефонные номера-это очень часто собираемые в Интернете данные.Например,при создании любого вида регистрационного сайта или сайта электронной коммерции,вам,скорее всего,придется запросить у пользователя номер телефона,будь то для бизнес-целей или для связи в экстренных случаях.Учитывая,насколько распространены телефонные номера,жаль,что «одноразмерное» решение для проверки телефонных номеров не является практичным.

К счастью, вы можете учесть требования своего сайта и самостоятельно реализовать соответствующий уровень проверки. Подробности см. в разделе Проверка ниже.

Custom keyboards

Одним из основных преимуществ <input type=»tel»> является то, что он заставляет мобильные браузеры отображать специальную клавиатуру для ввода телефонных номеров. Например, вот как выглядят клавиатуры на нескольких устройствах.

Firefox для Android WebKit iOS (Safari/Chrome/Firefox)

Простой тел-вход

В самом базовом виде вход tel может быть реализован таким образом:

Здесь нет ничего волшебного. При отправке на сервер указанные выше входные данные будут представлены, например, как telNo=+12125553151 .

Placeholders

Иногда бывает полезно предложить контекстную подсказку относительно того, какую форму должны принимать входные данные. Это может быть особенно важно, если дизайн страницы не предлагает описательных меток для каждого <input> . Это где заполнители бывают. Заполнитель этого значения , которое показывает , какую форму value следует принимать, представляя пример действительного значения, которое отображается в окне редактирования , когда элемент value является «» . После ввода данных в поле заполнитель исчезает; если поле пусто, заполнитель появляется снова.

Здесь у нас есть ввод tel с заполнителем 123-4567-8901 . Обратите внимание, как заполнитель исчезает и появляется снова, когда вы манипулируете содержимым поля редактирования.

Управление размером входного сигнала

Вы можете контролировать не только физическую длину поля ввода,но и минимальную и максимальную длину,разрешенную для самого вводимого текста.

Размер элемента физического ввода

Физическим размером поля ввода можно управлять с помощью атрибута size . С его помощью вы можете указать количество символов, которое поле ввода может отображать одновременно. В этом примере, например, поле редактирования tel имеет ширину 20 символов:

Длина элемента

size отделен от ограничения длины по введенному номеру телефона. Вы можете указать минимальную длину в символах для введенного телефонного номера с minlength атрибута minlength ; аналогично, используйте maxlength , чтобы установить максимальную длину введенного телефонного номера.

В примере,приведенном ниже,создается 20-символьное поле ввода телефонного номера,содержание которого должно быть не менее 9 символов и не более 14 символов.

Примечание. Приведенные выше атрибуты влияют на проверку — входные данные в приведенном выше примере будут считаться недействительными, если длина значения меньше 9 символов или больше 14. Большинство браузеров даже не позволят вам ввести значение, превышающее максимальную длину.

Предоставление опций по умолчанию

Предоставление одного значения по умолчанию с помощью атрибута value

Как всегда, вы можете указать значение по умолчанию для поля ввода tel , установив его атрибут value :

Предлагая предложенные значения

Сделав еще один шаг, вы можете предоставить список значений телефонных номеров по умолчанию, из которых пользователь может выбирать. Для этого используйте атрибут list . Это не ограничивает пользователя этими параметрами, но позволяет им быстрее выбирать часто используемые телефонные номера. Это также предлагает подсказки для autocomplete . list атрибутов определяет идентификатор <datalist> элемент, который , в свою очередь , содержит один <option> элемент каждого предлагаемого значения; каждый option «сек value является соответствующим предлагаемым значением для поля ввода номера телефона.

С элементом <datalist> и его <option> браузер предложит указанные значения в качестве возможных значений для номера телефона; обычно это представлено в виде всплывающего или раскрывающегося меню, содержащего предложения. Хотя конкретный пользовательский интерфейс может варьироваться от одного браузера к другому, обычно щелчок в поле редактирования представляет раскрывающийся список предлагаемых номеров телефонов. Затем, по мере ввода пользователем, список корректируется, чтобы отображать только отфильтрованные совпадающие значения. Каждый введенный символ сужает список до тех пор, пока пользователь не сделает выбор или не введет пользовательское значение.

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

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