паттерн для номера телефона javascript
Форматирование номеров телефона с помощью регулярных выражений
Такая элементарная вещь, как номер телефона, в письменных текстах живёт во множестве вариантов. Обыкновенный номер типа +7 (123) 123-45-67 можно встретить записанным без скобок или дефисов ( +7 123 1234567 ), а то и вообще без пробелов ( +71231234567 ). Не собираюсь оскорблять чувства пишущих, им и так непросто. Но уважающий себя веб-ресурс не может допустить такой типографической разношёрстности. Плюс к тому, необлагороженные номера неудобно читать человеку (то самое human-readable).
Данная статья о том, как привести все телефонные номера на странице к однообразному виду, а также проставить корректные ссылки типа tel: на них. Для решения поставленной задачи используются регулярные выражения JavaScript. Хороший обзор регэкспов дан здесь, также почитать по теме можно на MDN.
Найти все телефонные номера на странице можно таким способом:
Метод match() вернёт и запишет в переменную phoneNumbers массив (объект типа Array ) со всеми найденными на странице номерами.
Дисклеймер. Виденное выше регулярное выражение может вызвать сильное чувство боли в глазах у неподготовленного читателя. Если вы не очень знакомы с регулярками, автор всё-таки советует для начала проработать несколько первых глав учебника на LearnJavascript.
Разберём это выражение:
То есть, фактически, эти части паттерна распознают первые три цифры после кода страны, причём как взятые в скобки, так и без (квантификатор * синонимичен <0,>и означает «либо ноль, либо сколько угодно»).
Ну хорошо, найти все номера получилось. К сожалению, задача этим не исчерпывается. Как же взять и заменить все вхождения разом?
Но ведь у нас задача сложнее: нельзя же заменить разные номера телефонов на один! Тут самое время вспомнить о скобочных группах.
Скобочная группа — термин из теории регулярных выражений. Технически это просто часть паттерна, взятая в скобки. Но к любой такой группе можно обратиться по индексу.
То была идея, а теперь реализация:
В результате будет выведен аккуратный, каноничный телефонный номер. Работает!
Теперь, чтобы заменить все найденные номера телефонов на единообразные, добавим флаг g :
То есть, для корректной работы ссылки нужно в её коде выписать все цифры номера подряд — как раз самый неудобный для чтения человеком вариант.
Паттерн для номера телефона javascript
ВВЕДЕНИЕ
Данная заметка предназначена для тех, кто ищет простой и нормальный скрипт для маски телефонного номера. Почему это важно? Потому что зачастую пользователь сайта не понимает как именно и в каком формате вводить свой номер телефона, на подсказку внутри поля как правило никто не обращает внимания. Поэтому надо сделать так, чтобы он тупо вбивал цифры, а формат номера оставался неизменным. Об этом и речь
Что вы узнаете:
Что такое «паттерн» и что такое «маска»
Код выглядит примерно так:
Пример использования маски ввода
Введите свой номер телефона
Готовый скрипт для ввода телефонного номера
HTML код поля выглядит примерно так:
JS код скрипта:
Как подключить данный скрипт к Joomla
Скрипт подключается очень легко. Просто добавьте его в папку JS вашего шаблона, а в index.php там где подключаете скрипты добавьте строчку:
Кстати, на этом сайте я сразу же заменил все паттерны для телефонных номеров, все работает отлично на последней версии joomla. Само собой, что скрипт можно использовать не только на joomla, а где угодно.
Напоминаю, что вопросы можно задать в группе https://t.me/newqosgroup
Подписывайтесь на канал в Телеграм
Политика сайта
Помните что все статьи и мнения основаны на личном опыте группы людей, их мнение может не совпадать с общепринятым, либо с еще каким-нибудь другим мнением
Сайт не собирает абсолютно никакой конфиденциальной информации ни под каким предлогом
Сайт не поддерживает никакие меньшинства: радужных дней, флагов и прочей ерунды не будет
Паттерн для номера телефона javascript
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.
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:
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:
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.
Простой способ маски телефона и pattern input tel
Например, есть форма обратной связи с полем введите номер телефона.
Изначально без маски телефона можно ввести любой номер в любом формате даже с буквами.
Мы сделаем, чтобы ввод телефона строго соответствовал заданной маске.
Простой и эффективный способ это сделать с помощью плагина jquery.
Скачаем плагин с официального сайта jquery.
В поле поиска пишем mask и нажимаем на jQuery Masked Input.
Чтобы посмотреть инструкции работы плагина перейдем на github.
Из архива нам понадобится файл jquery.maskedinput.js.
Положим файл в папку с плагинами проекта libs и подключим новый плагин в файле gulpfile.js в том месте, где все подключенные скрипты упаковываются в один scripts.min.js.
Добавим скрипт, чтобы работала маска.
Для этого откроем инструкцию и для телефона с идентификатором phone скопируем строку в common.js.
Код в common.js.
Шаблон для номера телефона
Всем привет. У меня такой вопрос кто-нибудь знает RegExp шаблон для номера телефона (СНГ)? Желательно чтобы умел разбирать:
Буду рад любой помощи.
P.S. Пишу на JavaScript
3 ответа 3
Решил сделать так. Сначало отсеить все нецифровые значения номера, исключения сделать только для всяких скобо, дефисов, пробелов и т.д.
Потом привести их все к нормальному виду. Например вот так:
Ориентировано на российские мобильные + городские с кодом из 3 цифр (например, Москва). Пропускает:
Пользуюсь давно вот этой регуляркой и очень рад:
Всё ещё ищете ответ? Посмотрите другие вопросы с метками регулярные-выражения javascript или задайте свой вопрос.
Похожие
Подписаться на ленту
Для подписки на ленту скопируйте и вставьте эту ссылку в вашу программу для чтения RSS.
дизайн сайта / логотип © 2021 Stack Exchange Inc; материалы пользователей предоставляются на условиях лицензии cc by-sa. rev 2021.10.25.40561
Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.