Поле для телефона
Чтобы указать телефонный номер используйте для этого специальное поле. По своему виду и работе оно совпадает с текстовым полем. Синтаксис создания этого поля следующий.
<input type="tel" атрибуты>
Атрибуты полностью совпадают с текстовым полем.
В отличие от веб-адреса или адреса электронной почты, поле для телефона не проверяется на правильность синтаксиса. Это связано с тем, что телефонные номера в разных местах мира могут иметь самые разнообразные формы написания, включать цифры, буквы и другие символы. Смысл применения этого поля в настройке шаблона ввода телефона, который используется в определённом городе или стране, а также в некоторых расширенных возможностях по управлению стилями.
Создание поля для телефона показано в примере 1. Требуется ввести телефон в указанном формате, иначе браузер выведет сообщение об ошибке и не станет отправлять форму, пока поле не будет заполнено корректно.
Пример 1. Поле для телефона
HTML5IE 10+CrOpSaFx
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Телефон</title>
</head>
<body>
<form>
<p>Ваше имя: <input name="login"></p>
<p>Телефон в формате 2xxx-xxx: <input type="tel" name="tel"
pattern="2[0-9]{3}-[0-9]{3}"></p>
<p><input type="submit" value="Отправить"></p>
</form>
</body>
</html>
Результат примера при вводе неправильного телефона показан на рис. 1.
Рис. 1. Ввод телефона в браузере Chrome
Браузеры IE и Safari не поддерживают этот вид поля и соответственно не делают проверку на шаблон телефона.
HTML по теме
<input>
elements of type tel
are used to let the user enter and edit a telephone number. Unlike <input type="email">
and <input type="url">
, the input value is not automatically validated to a particular format before the form can be submitted, because formats for telephone numbers vary so much around the world.
Try it
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 <input>
element’s value
attribute contains a string 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.
list
The values of the list attribute is the id
of a <datalist>
element located in the same document. The <datalist>
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 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 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 a 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 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 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>
labels 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.
size
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 to activate automatic correction while the user is editing this field. Permitted values are:
on
-
Enable automatic correction of typos, as well as processing of text substitutions if any are configured.
off
-
Disable automatic correction and text substitutions.
mozactionhint
A Mozilla extension, 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 attribute has been deprecated: use the enterkeyhint
global attribute instead.
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) |
---|---|
|
|
A simple tel input
In its most basic form, a tel input can be implemented like this:
<label for="telNo">Phone number:</label>
<input id="telNo" name="telNo" type="tel" />
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.
<input id="telNo" name="telNo" type="tel" placeholder="123-4567-8901" />
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:
<input id="telNo" name="telNo" type="tel" size="20" />
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.
<input
id="telNo"
name="telNo"
type="tel"
size="20"
minlength="9"
maxlength="14" />
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:
<input id="telNo" name="telNo" type="tel" value="333-4444-4444" />
Offering suggested values
Taking it a step further, 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.
<label for="telNo">Phone number: </label>
<input id="telNo" name="telNo" type="tel" list="defaultTels" />
<datalist id="defaultTels">
<option value="111-1111-1111"></option>
<option value="122-2222-2222"></option>
<option value="333-3333-3333"></option>
<option value="344-4444-4444"></option>
</datalist>
With the <datalist>
element and its <option>
s in place, the browser will offer the specified values as potential values for the phone number; 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 phone numbers. 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.
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:
<form>
<div>
<label for="telNo">Enter a telephone number (required): </label>
<input id="telNo" name="telNo" type="tel" required />
<span class="validity"></span>
</div>
<div>
<button>Submit</button>
</div>
</form>
And let’s include the following CSS to highlight valid entries with a checkmark and invalid entries with a cross:
div {
margin-bottom: 10px;
position: relative;
}
input[type="number"] {
width: 100px;
}
input + span {
padding-right: 30px;
}
input:invalid + span::after {
position: absolute;
content: "✖";
padding-left: 5px;
color: #8b0000;
}
input:valid + span::after {
position: absolute;
content: "✓";
padding-left: 5px;
color: #009000;
}
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:
<form>
<div>
<label for="telNo">
Enter a telephone number (in the form xxx-xxx-xxxx):
</label>
<input
id="telNo"
name="telNo"
type="tel"
required
pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}" />
<span class="validity"></span>
</div>
<div>
<button>Submit</button>
</div>
</form>
div {
margin-bottom: 10px;
position: relative;
}
input[type="number"] {
width: 100px;
}
input + span {
padding-right: 30px;
}
input:invalid + span::after {
position: absolute;
content: "✖";
padding-left: 5px;
color: #8b0000;
}
input:valid + span::after {
position: absolute;
content: "✓";
padding-left: 5px;
color: #009000;
}
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 screen reader users about what to enter into it.
<form>
<div>
<label for="country">Choose your country:</label>
<select id="country" name="country">
<option>UK</option>
<option selected>US</option>
<option>Germany</option>
</select>
</div>
<div>
<p>Enter your telephone number:</p>
<span class="areaDiv">
<input
id="areaNo"
name="areaNo"
type="tel"
required
placeholder="Area code"
pattern="[0-9]{3}"
aria-label="Area code" />
<span class="validity"></span>
</span>
<span class="number1Div">
<input
id="number1"
name="number1"
type="tel"
required
placeholder="First part"
pattern="[0-9]{3}"
aria-label="First part of number" />
<span class="validity"></span>
</span>
<span class="number2Div">
<input
id="number2"
name="number2"
type="tel"
required
placeholder="Second part"
pattern="[0-9]{4}"
aria-label="Second part of number" />
<span class="validity"></span>
</span>
</div>
<div>
<button>Submit</button>
</div>
</form>
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.
const selectElem = document.querySelector("select");
const inputElems = document.querySelectorAll("input");
selectElem.onchange = () => {
for (let i = 0; i < inputElems.length; i++) {
inputElems[i].value = "";
}
if (selectElem.value === "US") {
inputElems[2].parentNode.style.display = "inline";
inputElems[0].placeholder = "Area code";
inputElems[0].pattern = "[0-9]{3}";
inputElems[1].placeholder = "First part";
inputElems[1].pattern = "[0-9]{3}";
inputElems[1].setAttribute("aria-label","First part of number");
inputElems[2].placeholder = "Second part";
inputElems[2].pattern = "[0-9]{4}";
inputElems[2].setAttribute("aria-label", "Second part of number");
} else if (selectElem.value === "UK") {
inputElems[2].parentNode.style.display = "none";
inputElems[0].placeholder = "Area code";
inputElems[0].pattern = "[0-9]{3,6}";
inputElems[1].placeholder = "Local number";
inputElems[1].pattern = "[0-9]{4,8}";
inputElems[1].setAttribute("aria-label", "Local number");
} else if (selectElem.value === "Germany") {
inputElems[2].parentNode.style.display = "inline";
inputElems[0].placeholder = "Area code";
inputElems[0].pattern = "[0-9]{3,5}";
inputElems[1].placeholder = "First part";
inputElems[1].pattern = "[0-9]{2,4}";
inputElems[1].setAttribute("aria-label","First part of number");
inputElems[2].placeholder = "Second part";
inputElems[2].pattern = "[0-9]{4}";
inputElems[2].setAttribute("aria-label","Second part of number");
}
}
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.
div {
margin-bottom: 10px;
position: relative;
}
input[type="number"] {
width: 100px;
}
input + span {
padding-right: 30px;
}
input:invalid + span::after {
position: absolute;
content: "✖";
padding-left: 5px;
color: #8b0000;
}
input:valid + span::after {
position: absolute;
content: "✓";
padding-left: 5px;
color: #009000;
}
Technical Summary
Value |
A string representing a telephone number, or empty |
|
Events |
change andinput
|
|
Supported common attributes |
autocomplete ,list ,maxlength ,minlength ,pattern ,placeholder ,readonly , andsize
|
|
IDL attributes |
list , selectionStart ,selectionEnd , selectionDirection , andvalue
|
|
DOM interface |
|
|
Methods |
select() ,setRangeText() ,setSelectionRange()
|
|
Implicit ARIA Role |
with no list attribute:textbox
|
with list attribute: combobox |
Specifications
Specification |
---|
HTML Standard # telephone-state-(type=tel) |
Browser compatibility
BCD tables only load in the browser
See also
Значение tel
Синтаксис
Описание
Тип tel
(от англ. «telephone» ‒ «телефон») создаёт поле ввода телефонного номера.
Внешний вид
Примечание
HTML спецификация не устанавливает определённый синтаксис телефонного номера для данного поля (в отличие от «url
» и «email
» полей). Это сделано намеренно, так как на практике, поля телефонных номеров, как правило, имеют свободную форму, потому что существует большое разнообразие допустимых телефонных номеров. (Установить необходимый синтаксис телефонного номера можно с помощью атрибута «pattern
».)
Поддержка браузерами
Спецификация
Сопутствующие атрибуты
- autocomplete
- Автозаполнение значения поля телефона.
- autofocus
- Автоматческая фокусировка на телефонном поле после полной загрузки страницы.
- disabled
- Блокировка поля телефона.
disabled="disabled"
- form
- Присоединение телефонного поле к форме.
- list
- Создание списка рекомендованных вариантов телефонных номеров.
- maxlength
- Задаёт максимально-допустимое количество вводимых символов.
- minlength
- Задаёт минимально-допустимое количество вводимых символов.
- name
- Присваивает имя телефонному полю.
- pattern
- Устанавливает критерий/шаблон ввода.
- placeholder
- Указывает текст-подсказку для пустого поля.
placeholder="Текст-подсказка"
- readonly
- Указывает, что поле телефона доступно только для чтения (изменение/редактирование запрещено).
- required
- Указывает, что поле телефона обязательно для заполнения.
- size
- Задаёт ширину телефонного поля по количеству вводимых символов.
size="10"
- value
- Указывает значение телефонного поля (отправляется на сервер или используется скриптами).
Примечание: Данный атрибут должен иметь значение, которое не содержит символов «LF» ПЕРЕВОД СТРОКИ [
U+000A
] или «CR» ВОЗВРАТ КАРЕТКИ [U+000D
].value="+7 (900) 123-45-67"
- Глобальные атрибуты
- accesskey, class, contenteditable, data-*, dir, draggable, dropzone, hidden, id, inert, lang, spellcheck, style, tabindex, title, translate, xml:lang
Пример использования
<!DOCTYPE html>
<html>
<head>
<meta charset=«utf-8»>
<title>Значение tel (input-type)</title>
</head>
<body>
<h1>Пример с полем ввода телефонного номера «type=tel»</h1>
<form action=«/examples/php-scripts/telephone.php» method=«post»>
<fieldset> <legend>Введите ваш номер телефона</legend>
<p><input type=«tel» name=«phone_number» list=«tel-list» placeholder=«+7 (900) 123-45-67» pattern=«+7s?[(]{0,1}9[0-9]{2}[)]{0,1}s?d{3}[-]{0,1}d{2}[-]{0,1}d{2}»></p>
<datalist id=«tel-list»>
<option value=«+7 (900) 123-45-67» label=«Телефонный номер №1»>
<option value=«+7 (900) 123-45-68» label=«Телефонный номер №2»>
</datalist>
</fieldset>
<p><input type=«reset»> <input type=«submit»></p>
</form>
</body>
</html>
Значение tel (input-type)
Type tel значение телефона атрибут поля ввода input
Тип «tel» — телефон(телефонный номер). Что такое type tel html, Type tel — это одно из значений тега input, предназначено для ввода телефонного номера по шаблону «pattern».
Тип телефон в поле ввода input
- Что такое type tel html,
- Пример использования type tel.
У поля ввода есть типы передаваемых данных type, с разными значениями input
Одно из таких значении : «type tel» — который предназначен для ввода телефонного номера.
Синтаксис type tel html.
<input type=»tel»>
Характеристики типа tel :
«type tel» — это поле предназначено для ввода номера телефона.
Кроме самого атрибута type со значением tel необходимо использовать формат телефонного номера, это атрибут «pattern»
pattern=»[0-9]{1}-[0-9]{3}-[0-9]{3}»
Как использовать данный type tel на сайте.
Кроме поле ввода , мы можем добавит вовнутрь подсказку placeholder:
Понадобится форма form.
<form method=»post»>
<input name=»phone» type=»tel» pattern=»[0-9]{1}-[0-9]{3}-[0-9]{3}» placeholder=»Номер телефона»>
<input name=»phone_submit» type=»submit» value=»Отправить»>
</form>
И еще одно поле ввода с другим типом submit
PHP :
Вам потребуется метод post.
Пример использования type tel.
Простое условие, по которому будем получать телефонный номер из поля с типом type tel
if($_POST[‘phone_submit’]) { $result = ‘Вы нажали кнопку отправить submit, переданное значение : ‘.strip_tags($_POST[‘phone’]) ;}
echo $result;
Соберем весь код вместе для type tel:
Html :
<form method=»post»>
<input name=»phone» type=»tel» pattern=»[0-9]{1}-[0-9]{3}-[0-9]{3}» placeholder=»Номер телефона»>
<input name=»phone_submit» type=»submit» value=»Отправить»>
</form>
if($_POST[‘phone_submit’]) { $result = ‘Вы нажали кнопку отправить submit, переданное значение : ‘.strip_tags($_POST[‘phone’]) ;}
echo $result;
Результат:
Введите номер телефона по шаблону, либо не по шаблону type tel и нажмите отправить:
Можете не благодарить, лучше помогите!
COMMENTS+
BBcode
I want to mark up a phone number as callable link in an HTML document. I have read the microformats approach, and I know, that the tel:
scheme would be standard, but is quite literally nowhere implemented.
Skype defines, as far as I know, skype:
and callto:
, the latter having gained some popularity. I assume, that other companies have either other schemes or jump on the callto:
train.
What would be a best practice to mark-up a phone number, so that as many people as possible with VoIP software can just click on a link to get a call?
Bonus question: Does anyone know about complications with emergency numbers such as 911 in US or 110 in Germany?
Update: Microsoft NetMeeting takes callto:
schemes under WinXP. This question suggests, that Microsoft Office Communicator will handle tel:
schemes but not callto:
ones. Great, Redmond!
Update 2: Two and a half years later now. It seems to boil down to what you want to do with the number. In mobile context, tel:
is the way to go. Targeting desktops it’s up to you, if you think your users are more Skype people (callto:
) or will more likely have something like Google Voice (tel:
) installed. My personal opinion is, when in doubt use tel:
(in line with @Sidnicious’ answer).
Update 3: User @rybo111 noted, that Skype in Chrome has meanwhile jumped on the tel:
bandwagon. I cannot verify this, because no machine with both at hand, but if it’s true, it means we have finally a winner here: tel:
Improve Article
Save Article
Improve Article
Save Article
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
- Create an HTML document that contains an <input> tag.
- Use the type attribute with the <input> tag which is set to value “tel”.
Syntax
<input type="tel">
Example 1:
HTML
<!DOCTYPE html>
<
html
>
<
head
>
<
title
>
How to add a Telephone number
into a Form using HTML5
</
title
>
<
style
>
#Geek_p {
font-size: 30px;
color: green;
}
h1,
h2 {
font-family: impact;
}
</
style
>
</
head
>
<
body
style
=
"text-align: center"
>
<
h1
style
=
"color: green"
>GeeksForGeeks</
h1
>
<
h2
>
How to add a Telephone number
into a Form using HTML5
</
h2
>
<
form
>
Name:
<
input
type
=
"text"
placeholder
=
"Enter your name here--"
/>
<
br
/>
Address:
<
input
type
=
"text"
placeholder
=
"Enter your permanent Address"
/>
<
br
/>
Phone No.:
<
input
type
=
"tel"
placeholder
=
"Enter phone number"
/>
<
br
/>
<
br
/>
<
button
>Submit</
button
>
</
form
>
</
body
>
</
html
>
Output:
Example 2:
HTML
<!DOCTYPE html>
<
html
>
<
head
>
<
title
>
How to add a Telephone number
into a Form using HTML5
</
title
>
<
style
>
#Geek_p {
font-size: 30px;
color: green;
}
h1,
h2 {
font-family: impact;
}
</
style
>
</
head
>
<
body
style
=
"text-align: center"
>
<
h1
style
=
"color: green"
>
GeeksForGeeks
</
h1
>
<
h2
>
How to add a Telephone number
into a Form using HTML5
</
h2
>
<
form
>
Phone No.:
<
input
type
=
"tel"
placeholder
=
"Enter phone number"
/>
<
br
/>
<
br
/>
<
button
>Get OTP</
button
>
</
form
>
</
body
>
</
html
>
Output:
Чтобы ввести телефонный номер в форме используйте для этого специальное поле, по своему виду и работе оно совпадает с текстовым полем. Синтаксис создания поля для телефона следующий.
<input type="tel" атрибуты>
Атрибуты полностью совпадают с текстовым полем.
В отличие от веб-адреса или адреса электронной почты, поле для телефона не проверяется на правильность синтаксиса. Это связано с тем, что телефонные номера в разных местах мира могут иметь самые разнообразные формы написания, включать цифры, буквы и другие символы. Смысл применения этого поля в настройке шаблона ввода телефона, который используется в определённом городе или стране, а также в некоторых расширенных возможностях по управлению стилями. Кроме того, при вводе номера телефона с планшета или смартфона меняется вид клавиатуры.
Создание поля для телефона показано в примере 1. Требуется ввести телефон в указанном формате, иначе браузер выведет сообщение об ошибке и не станет отправлять форму, пока поле не будет заполнено корректно.
Пример 1. Поле для телефона
<!DOCTYPE html>
<html>
<head>
<meta charset=»utf-8″>
<title>Телефон</title>
</head>
<body>
<form>
<p>Ваше имя: <input name=»login»></p>
<p>Телефон в формате 2xxx-xxx: <input type=»tel» name=»tel»
pattern=»2[0-9]{3}-[0-9]{3}»></p>
<p><input type=»submit» value=»Отправить»></p>
</form>
</body>
</html>
Результат примера при вводе неправильного телефона показан на рис. 1.
Рис. 1. Ввод телефона
Для обычного текстового поля клавиатура планшета имеет стандартный вид (рис. 2).
Рис. 2. Вид клавиатуры для ввода текста
Однако при вводе телефона клавиатура меняет свой вид (рис. 3). Система сама определяет, что пользователь вводит номер и подстраивается под него.
Рис. 3. Вид клавиатуры для ввода телефона
Последнее изменение: 11.03.2020
<input type=»tel»>
<input>
Элементы <input> типа tel
позволяют пользователю вводить и редактировать телефонный номер. В отличие от <input type="email">
и <input type="url">
, входное значение не проверяется автоматически на определенный формат перед отправкой формы, потому что форматы телефонных номеров сильно различаются по всему миру.
Try it
Несмотря на то, что вводы типа tel
функционально идентичны стандартным text
вводам, они служат полезным целям; наиболее очевидным из них является то, что мобильные браузеры — особенно на мобильных телефонах — могут отображать настраиваемую клавиатуру, оптимизированную для ввода телефонных номеров. Использование определенного типа ввода для телефонных номеров также делает добавление пользовательской проверки и обработки телефонных номеров более удобными.
Примечание. Браузеры, не поддерживающие тип tel
, возвращаются к стандартному вводу текста .
Value | Строка,представляющая телефонный номер,или пустая |
Events | change и input |
Поддерживаемые общие атрибуты | autocomplete , list , maxlength , minlength , pattern , placeholder , только readonly и size |
IDL attributes | list , selectionStart , selectionEnd , selectionDirection и value |
DOM interface |
|
Methods | select() , setRangeText() , setSelectionRange() |
Value
Атрибут value
элемента <input>
содержит строку, которая либо представляет номер телефона, либо является пустой строкой ( ""
). value
""
Additional attributes
В дополнение к атрибутам, которые работают со всеми элементами <input>
независимо от их типа, входы телефонных номеров поддерживают следующие атрибуты.
list
Значения атрибута 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
size
атрибут является числовым значением , указывающим , сколько символов в ширине поле ввода должно быть. Значение должно быть числом больше нуля, а значение по умолчанию — 20. Поскольку ширина символов различается, это может быть или не быть точным, и на это не следует полагаться; результирующий ввод может быть уже или шире, чем указанное количество символов, в зависимости от символов и шрифта (используемых настроек font
).
Это не устанавливает ограничения на количество символов, которые пользователь может ввести в поле. Он лишь указывает приблизительно, сколько можно увидеть одновременно. Чтобы установить верхний предел длины входных данных, используйте атрибут maxlength
.
Non-standard attributes
Следующие нестандартные атрибуты доступны для полей ввода телефонных номеров.Как правило,вы должны избегать их использования,если только это не поможет.
autocorrect
В расширении Safari атрибут autocorrect
представляет собой строку, которая указывает, следует ли активировать автоматическое исправление, когда пользователь редактирует это поле. Допустимые значения:
on
-
Включает автоматическую коррекцию опечаток,а также обработку подстановок текста,если они настроены.
off
-
Отключить автоматическое исправление и замену текста.
mozactionhint
Расширение Mozilla,которое дает подсказку о том,какое действие будет предпринято,если пользователь нажмет кнопкуEnterorReturnво время редактирования поля.
Этот атрибут устарел: вместо него используйте глобальный атрибут enterkeyhint
.
Использование тел-входов
Телефонные номера-это очень часто собираемые в Интернете данные.Например,при создании любого вида регистрационного сайта или сайта электронной коммерции,вам,скорее всего,придется запросить у пользователя номер телефона,будь то для бизнес-целей или для связи в экстренных случаях.Учитывая,насколько распространены телефонные номера,жаль,что «одноразмерное» решение для проверки телефонных номеров не является практичным.
К счастью, вы можете учесть требования своего сайта и самостоятельно реализовать соответствующий уровень проверки. Подробности см. в разделе Проверка ниже.
Custom keyboards
Одним из основных преимуществ <input type="tel">
является то, что он заставляет мобильные браузеры отображать специальную клавиатуру для ввода телефонных номеров. Например, вот как выглядят клавиатуры на нескольких устройствах.
Простой тел-вход
В самом базовом виде вход tel может быть реализован таким образом:
<label for="telNo">Phone number:</label> <input id="telNo" name="telNo" type="tel">
Здесь нет ничего волшебного. При отправке на сервер указанные выше входные данные будут представлены, например, как telNo=+12125553151
.
Placeholders
Иногда бывает полезно предложить контекстную подсказку относительно того, какую форму должны принимать входные данные. Это может быть особенно важно, если дизайн страницы не предлагает описательных меток для каждого <input>
. Это где заполнители бывают. Заполнитель этого значения , которое показывает , какую форму value
следует принимать, представляя пример действительного значения, которое отображается в окне редактирования , когда элемент value
является ""
. После ввода данных в поле заполнитель исчезает; если поле пусто, заполнитель появляется снова.
Здесь у нас есть ввод tel
с заполнителем 123-4567-8901
. Обратите внимание, как заполнитель исчезает и появляется снова, когда вы манипулируете содержимым поля редактирования.
<input id="telNo" name="telNo" type="tel" placeholder="123-4567-8901">
Управление размером входного сигнала
Вы можете контролировать не только физическую длину поля ввода,но и минимальную и максимальную длину,разрешенную для самого вводимого текста.
Размер элемента физического ввода
Физическим размером поля ввода можно управлять с помощью атрибута size
. С его помощью вы можете указать количество символов, которое поле ввода может отображать одновременно. В этом примере, например, поле редактирования tel
имеет ширину 20 символов:
<input id="telNo" name="telNo" type="tel" size="20">
Длина элемента
size
отделен от ограничения длины по введенному номеру телефона. Вы можете указать минимальную длину в символах для введенного телефонного номера с minlength
атрибута minlength ; аналогично, используйте maxlength
, чтобы установить максимальную длину введенного телефонного номера.
В примере,приведенном ниже,создается 20-символьное поле ввода телефонного номера,содержание которого должно быть не менее 9 символов и не более 14 символов.
<input id="telNo" name="telNo" type="tel" size="20" minlength="9" maxlength="14">
Примечание. Приведенные выше атрибуты влияют на проверку — входные данные в приведенном выше примере будут считаться недействительными, если длина значения меньше 9 символов или больше 14. Большинство браузеров даже не позволят вам ввести значение, превышающее максимальную длину.
Предоставление опций по умолчанию
Предоставление одного значения по умолчанию с помощью атрибута value
Как всегда, вы можете указать значение по умолчанию для поля ввода tel
, установив его атрибут value
:
<input id="telNo" name="telNo" type="tel" value="333-4444-4444">
Предлагая предложенные значения
Сделав еще один шаг, вы можете предоставить список значений телефонных номеров по умолчанию, из которых пользователь может выбирать. Для этого используйте атрибут list
. Это не ограничивает пользователя этими параметрами, но позволяет им быстрее выбирать часто используемые телефонные номера. Это также предлагает подсказки для autocomplete
. list
атрибутов определяет идентификатор <datalist>
элемент, который , в свою очередь , содержит один <option>
элемент каждого предлагаемого значения; каждый option
«сек value
является соответствующим предлагаемым значением для поля ввода номера телефона.
<label for="telNo">Phone number: </label> <input id="telNo" name="telNo" type="tel" list="defaultTels"> <datalist id="defaultTels"> <option value="111-1111-1111"> <option value="122-2222-2222"> <option value="333-3333-3333"> <option value="344-4444-4444"> </datalist>
С элементом <datalist>
и его <option>
браузер предложит указанные значения в качестве возможных значений для номера телефона; обычно это представлено в виде всплывающего или раскрывающегося меню, содержащего предложения. Хотя конкретный пользовательский интерфейс может варьироваться от одного браузера к другому, обычно щелчок в поле редактирования представляет раскрывающийся список предлагаемых номеров телефонов. Затем, по мере ввода пользователем, список корректируется, чтобы отображать только отфильтрованные совпадающие значения. Каждый введенный символ сужает список до тех пор, пока пользователь не сделает выбор или не введет пользовательское значение.
Вот скриншот того,как это может выглядеть:
© 2005–2022 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/tel
HTML
-
Размер элемента физического ввода
Физический размер поля ввода можно контролировать с помощью атрибута.
-
<input type=»submit»>
Элементы <input> типа submit отображаются как кнопки.
-
Validation
Как мы уже упоминали ранее, довольно сложно предоставить универсальные телефонные номера решения для проверки на стороне клиента.
-
<input type=»text»>
Элементы <input> типа text создают базовые однострочные поля.
Displaying a phone number on your website can help increase trust in your business, attract prospective customers, and delight existing ones.
To make it as easy as possible for users to get in touch with you or someone on your team, you can make the phone number clickable in HTML. This is a great UX strategy considering that mobile accounts for approximately half of web traffic worldwide. Meaning, over half of your website visitors will be using the same device to find your business online and to place the call.
In this post, we’ll walk through the process of creating HTML telephone links, or “click to call” links.
How to Link a Telephone Number in HTML
- Create an anchor element.
- Enter your phone number in the href attribute.
- Add tel: before the number inside the quotation marks.
- Include text in the anchor element.
1. Create an anchor element.
To start, create an anchor element with an empty href attribute. It will look like this:
<a href=""></a>
2. Enter your phone number in the href attribute.
Place the phone number inside the href attribute inside the opening a tag. This href (hypertext reference) attribute ensures the hyperlink is functional. It will look like this:
<a href="6031112298"></a>
3. Add tel: before the number inside the quotation marks.
Now add tel: inside the href attribute, before the phone number. Both the tel: and phone number should be inside the quotation marks with no spaces or dashes. It will look like this:
<a href="tel:6031112298"></a>
4. Include text in the anchor element.
You can include text in the anchor element. Although it’s not required, it can make the call-to-action more obvious to users. Here’s the code side by side with how it would appear to users on the front end of a website.
See the Pen How to Link a Telephone Number in HTML [With Linked Text] by HubSpot (@hubspot) on CodePen.
If you’d like to include the telephone number and have it be the only text that’s linked, then wrap the phone number in the anchor element and place it inside a paragraph tag. It will look like this:
See the Pen How to Link a Telephone Number in HTML [With Text] by HubSpot (@hubspot) on CodePen.
How to Link a Telephone Number With an Extension in HTML
If the telephone number you’d like to make clickable has an extension, then you’ll need to take an additional step.
- You create an anchor element.
- Enter tel: and the phone number in the href attribute.
- Now, after the phone number, add the letter “p” and the extension number. It will look like this:
<a href="tel:6031112298p000"></a>
When clicking this “click to call” link, the user will hear the number dialed, then a one-second pause, then the extension dialed.
How to Link a Telephone Number With a Country Code in HTML
If the telephone number you’d like to make clickable has a country code, then you’ll need to take a different additional step.
- You create an anchor element.
- Enter tel: and the phone number in the href attribute.
- Now, before the phone number, add the plus icon (+) and the country code. It will look like this:
<a href="tel:+16031112298p000"></a>
How to Add a HTML Telephone Link to Your Website
An HTML telephone link, or “click to call” link, can be included in various parts of your website. Your contact page and header or footer are among the most common. Let’s look at examples of including these clickable links on a WordPress website.
Contact Page
The exact steps to add a HTML telephone link to a contact page will vary depending on what platform and template you use. Below is the general process.
- To start, select a predesigned contact page template.
- Then click into the block with the example phone number.
- Click the three dots icon.
- Click Edit as HTML.
- Replace the existing phone number with the anchor element: <a href=»tel:6031112298″>(603)111-2298</a>
- Click Save Draft and Preview.
Header and Footer
The exact steps to add a HTML telephone link to a header or footer will vary depending on what platform and template you use. Below is the general process.
- In your dashboard, click Appearance > Widgets.
- In the section labelled “Footer,” add any blocks that you want. For the sake of this demo, I’ll only add a paragraph block.
- When you’re ready, click Update.
- Now go to one of your pages.
- Scroll down to the footer area and click the paragraph block.
- Add your phone number, then click the three dots icon.
- Click Edit as HTML.
- Wrap the phone number in an anchor element and add href=»tel:6031112298″ to the opening tag.
- Click Save Draft and Preview.
How to style a HTML Telephone Link
To style a HTML telephone link, you’ll have to add some custom CSS.
For example, say you want the telephone number to appear bolded, orange, and with no underline. Here’s the CSS and how the “click to call” link would appear on the front end:
See the Pen How to style a HTML Telephone Link by HubSpot (@hubspot) on CodePen.
How you add this CSS to your website depends on the platform you’re using. If building your site in WordPress, for example, you’d add this CSS to the Additional CSS tab in the WordPress Customizer.
Adding “Click to Call” Links to Your Website
Displaying a phone number on your website can help attract and delight prospective and existing customers — making them clickable is even better for UX. The good news is that creating telephone links is easy. You just need to know some HTML and CSS to create and style these links and embed them in different areas on your site.