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

Выражение Пример Описание
d или [0-9] Одна цифра от 0 до 9
D или [^0-9] Любой символ кроме цифры
s Один пробел
[A-Z] Только заглавная латинская буква
[A-Za-z] Только латинская буква в любом регистре
[А-Яа-яЁё] Только русская буква в любом регистре
[A-Za-zА-Яа-яЁё] Любая буква русского и латинского алфавита
[0-9]{3} Три цифры
[A-Za-z]{6,} Не менее шести латинских букв
[0-9]{,3} Не более трёх цифр
[0-9]{5,10} От пяти до десяти цифр
^[a-zA-Z]+$ Любое слово на латинице
^[А-Яа-яЁёs]+$ Любое слово на русском включая пробелы
^[ 0-9]+$ Любое число
[0-9]{6} Почтовый индекс
d+(,d{2})? Число в формате 2,4 (разделитель запятая)
d+(.d{2})? Число в формате 5.72 (разделитель точка)
d{1,3}.d{1,3}.d{1,3}.d{1,3} IP-адрес
[A-z]{2} 2х буквенный код страны
[A-z]{3} 3х буквенный код страны
(?=^.{8,}$)((?=.*d)|(?=.*W+))(?![.n])(?=.*[A-Z])(?=.*[a-z]).* Поле пароля: Минимум 8 символов, одна цифра, одна буква в верхнем регистре и одна в нижнем
^#+([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$ цвет в шестнадцатеричном виде, например #3b5998 или #000
[x1F-xBF]* в данном поле разрешены все символы кроме кирилицы
[0-9]{10,12} ИНН юридического лица или ИП. Для полной проверки используйте пример
[0-9]{10,12} ИНН:
КПП:
ИНН + КПП юридического лица или ИП. Для полной проверки используйте пример
+7s?[(]{0,1}9[0-9]{2}[)]{0,1}s?d{3}[-]{0,1}d{2}[-]{0,1}d{2} Номер телефона
(+7[-_()s]+|+7s?[(]{0,1}[0-9]{3}[)]{0,1}s?d{3}[-]{0,1}d{2}[-]{0,1}d{2}) Номер телефона или пусто

HTML Проверка номера телефона

<p>Введите телефон в формате +7-xxx-xxx-xx-xx, где вместо x должна быть цифра:</p>
<p><input type="tel" pattern="+7-[0-9]{3}-[0-9]{3}-[0-9]{2}-[0-9]{2}"></p>
<p><input type="submit" value="Отправить"></p>

Mask на чистом javascript

Более сложная проверка вводимого номера телефона в input-поле с проверкой и подстановкой дополнительных символов:

<form>
  <label for="online_phone">Телефон:</label>
  <input id="online_phone" name="phone" type="tel" maxlength="50"
         autofocus="autofocus" required="required"
         value="+7(___)___-__-__"
         pattern="+7s?[(]{0,1}9[0-9]{2}[)]{0,1}s?d{3}[-]{0,1}d{2}[-]{0,1}d{2}"
         placeholder="+7(___)___-__-__">
</form>
<script type="text/javascript">
  function setCursorPosition(pos, e) {
    e.focus();
    if (e.setSelectionRange) e.setSelectionRange(pos, pos);
    else if (e.createTextRange) {
      var range = e.createTextRange();
      range.collapse(true);
      range.moveEnd("character", pos);
      range.moveStart("character", pos);
      range.select()
    }
  }

  function mask(e) {
    //console.log('mask',e);
    var matrix = this.placeholder,// .defaultValue
        i = 0,
        def = matrix.replace(/D/g, ""),
        val = this.value.replace(/D/g, "");
    def.length >= val.length && (val = def);
    matrix = matrix.replace(/[_d]/g, function(a) {
      return val.charAt(i++) || "_"
    });
    this.value = matrix;
    i = matrix.lastIndexOf(val.substr(-1));
    i < matrix.length && matrix != this.placeholder ? i++ : i = matrix.indexOf("_");
    setCursorPosition(i, this)
  }
  window.addEventListener("DOMContentLoaded", function() {
    var input = document.querySelector("#online_phone");
    input.addEventListener("input", mask, false);
    input.focus();
    setCursorPosition(3, input);
  });
</script>

HTML Проверка даты

<p>Введите дату в формате дд.мм.гггг:</p>
<p><input type="date" pattern="[0-9]{2}.[0-9]{2}.[0-9]{4}"></p>
<p><input type="submit" value="Отправить"></p>

Метод checkValidity() может быть выполнен на любом отдельном поле или формы в целом,
вернув true или false – соответствует шаблону или нет.

<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

{{page(«/en-US/docs/Web/HTML/Element/input/text», «pattern-include»)}}

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.

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.

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

{{page(«/en-US/docs/Web/HTML/Element/input/text», «autocorrect-include»)}}

mozactionhint
Non-standard

{{page(«/en-US/docs/Web/HTML/Element/input/text», «mozactionhint-include»)}}

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:

<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">

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

<input id="telNo" name="telNo" type="tel"
       value="333-4444-4444">

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.

<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>

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:

<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 screenreader 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.

var selectElem = document.querySelector("select");
var inputElems = document.querySelectorAll("input");

selectElem.onchange = function() {
  for(var 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;
}

Specifications

Browser compatibility

BCD tables only load in the browser

See also

I’m using HTML5 form validation to validate phone numbers from India.

Phone numbers from India are 10 digits long, and start with 7, 8, or 9.

For example:

  1. 7878787878
  2. 9898989898
  3. 8678678878

These phone numbers are valid, but

  1. 1212121212
  2. 3434545464
  3. 6545432322

are invalid.

Suggest a pattern that can detect valid India phone numbers.

So far, my pattern is [0-9]{10}, but it doesn’t check if the first digit is 7, 8, or 9.

Zim's user avatar

Zim

3881 gold badge4 silver badges15 bronze badges

asked Oct 26, 2013 at 20:33

Manwal's user avatar

3

How about

<input type="text" pattern="[789][0-9]{9}">

answered Oct 26, 2013 at 20:40

JamesPlayer's user avatar

JamesPlayerJamesPlayer

1,8141 gold badge15 silver badges20 bronze badges

1

How about this? /(7|8|9)d{9}/

It starts by either looking for 7 or 8 or 9, and then followed by 9 digits.

answered Oct 26, 2013 at 20:37

itsmikem's user avatar

itsmikemitsmikem

2,0882 gold badges26 silver badges29 bronze badges

7

The regex validation for india should make sure that +91 is used, then make sure that 7, 8,9 is used after +91 and finally followed by 9 digits.

/^+91(7d|8d|9d)d{9}$/

Your original regex doesn’t require a «+» at the front though.

Get the more information from below link
w3schools.com/jsref/jsref_obj_regexp.asp

answered Oct 26, 2013 at 20:42

Shailendr singh's user avatar

1

Try this code:

<input type="text" name="Phone Number" pattern="[7-9]{1}[0-9]{9}" 
       title="Phone number with 7-9 and remaing 9 digit with 0-9">

This code will inputs only in the following format:

9238726384 (starting with 9 or 8 or 7 and other 9 digit using any number)
8237373746
7383673874

Incorrect format:
2937389471(starting not with 9 or 8 or 7)
32796432796(more than 10 digit)
921543(less than 10 digit)

sam's user avatar

sam

1,7471 gold badge24 silver badges44 bronze badges

answered May 3, 2014 at 11:10

thejustv's user avatar

thejustvthejustv

1,98125 silver badges42 bronze badges

1

This code will accept all country code with + sign

<input type="text" pattern="[0-9]{5}[-][0-9]{7}[-][0-9]{1}"/>

Some countries allow a single «0» character instead of «+» and others a double «0» character instead of the «+». Neither are standard.

Ben Thomas's user avatar

Ben Thomas

3,1422 gold badges19 silver badges38 bronze badges

answered Oct 8, 2015 at 9:38

manish1706's user avatar

manish1706manish1706

1,53124 silver badges21 bronze badges

1

Improving @JamesPlayer’s answer:

Since now in India, a new series of phone numbers started with 6. Use this 👇

<input type="text" pattern="[6789][0-9]{9}">

To show a custom error message, use the title attribute.

<input type="text" pattern="[6789][0-9]{9}" title="Please enter valid phone number">

That’s all folks. 🎉

answered Apr 25, 2021 at 12:03

Darshan Gada's user avatar

2

enter image description here

^[789]d{9,9}$

  • Minimum digits 10
  • Maximum digits 10
  • number starts with 7,8,9

answered Dec 14, 2020 at 1:09

bunny's user avatar

bunnybunny

1,2462 gold badges11 silver badges22 bronze badges

Internet Explorer Chrome Opera Safari Firefox Android iOS
10.0 5.0+ 9.6+ 4.0+ 2.3+ 3.0+

Спецификация

HTML: 3.2 4.01 5.0 XHTML: 1.0 1.1

Описание

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

Синтаксис

<input type="email" pattern="выражение">
<input type="tel" pattern="выражение">
<input type="text" pattern="выражение">
<input type="search" pattern="выражение">
<input type="url" pattern="выражение">

Значения

Некоторые типовые регулярные выражения перечислены в табл. 1.

Табл. 1. Регулярные выражения

Выражение Описание
d
[0-9]
Одна цифра от 0 до 9.
D
[^0-9]
Любой символ кроме цифры.
s Пробел.
[A-Z] Только заглавная латинская буква.
[A-Za-z] Только латинская буква в любом регистре.
[А-Яа-яЁё] Только русская буква в любом регистре.
[A-Za-zА-Яа-яЁё] Любая буква русского и латинского алфавита.
[0-9]{3} Три цифры.
[A-Za-z]{6,} Не менее шести латинских букв.
[0-9]{,3} Не более трёх цифр.
[0-9]{5,10} От пяти до десяти цифр.
^[a-zA-Z]+$ Любое слово на латинице.
^[А-Яа-яЁёs]+$ Любое слово на русском включая пробелы.
^[ 0-9]+$ Любое число.
[0-9]{6} Почтовый индекс.
d+(,d{2})? Число в формате 1,34 (разделитель запятая).
d+(.d{2})? Число в формате 2.10 (разделитель точка).
d{1,3}.d{1,3}.d{1,3}.d{1,3} IP-адрес

Пример

HTML5IECrOpSaFx

<!DOCTYPE html>
<html>
 <head>
  <meta charset="utf-8">
  <title>Атрибут pattern</title>
 </head>
  <body>
   <form>
    <p>Введите телефон в формате 2-xxx-xxx, где вместо x 
    должна быть цифра:</p>
    <p><input type="tel" pattern="2-[0-9]{3}-[0-9]{3}"></p>
    <p><input type="submit" value="Отправить"></p>
   </form>
  </body>
</html>

Статьи по теме

Валидация форм. Атрибут pattern в HTML5

От автора: приветствую вас, друзья. В предыдущей статье мы достаточно легко и просто реализовали простейший механизм валидации полей формы, используя типы полей email и url. Однако таким образом мы можем проверить только ограниченный набор форматов данных. Как же быть? Все просто — используем атрибут HTML5 — pfttern. Приступим.

Исходные файлы текущей статьи вы можете скачать по ссылке.

Итак, возьмем код из предыдущего урока. В форме у нас имеется поле для ввода телефона, которое имеет тип tel:

<input type=«tel» class=«form-control» id=«phone» name=«phone» placeholder=«Телефон» required>

Практический курс по верстке адаптивного сайта с нуля!

Изучите курс и узнайте, как верстать современные сайты на HTML5 и CSS3

Узнать подробнее

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

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

Итак, давайте составим шаблон регулярного выражения, который будет пропускать только телефоны, скажем, следующего формата: (XXX) XXX-XX-XX (об этом формате обязательно уведомить пользователя в описании поля).

<input type=«tel» class=«form-control» id=«phone» name=«phone» placeholder=«Телефон в формате (XXX) XXX-XX-XX» pattern=«(d{3}) d{3}-d{2}-d{2}» required>

И проверим, сработает ли наш шаблон:

Работает! Если ввести строку, не соответствующую заданному шаблону, браузер сообщит об этом. Точно таким же образом мы можем проверять любые данные, поскольку регулярные выражения позволяют очень гибко организовать проверку на соответствие нужному формату данных.

Например, в качестве имени я хочу разрешить только буквы и пробелы, ничего кроме. Это просто:

<input type=«text» class=«form-control» id=«name» name=«name» placeholder=«Имя» pattern=«[a-zA-Zа-яА-ЯёЁ ]+» required>

Теперь если попробовать ввести в качестве имени что-то, не подходящее формату, получим предупреждение:

Замечательно, не так ли? На этом данную статью можно завершать. Дополнительно по данной теме вы можете посмотреть этот урок. На этом все. Удачи!

Практический курс по верстке адаптивного сайта с нуля!

Изучите курс и узнайте, как верстать современные сайты на HTML5 и CSS3

Узнать подробнее

Верстка. Быстрый старт

Практический курс по верстке адаптивного сайта с нуля!

Смотреть

Type tel значение телефона атрибут поля ввода input

Тип «tel» — телефон(телефонный номер). Что такое type tel html, Type tel — это одно из значений тега input, предназначено для ввода телефонного номера по шаблону «pattern».

Тип телефон в поле ввода input

  1. Что такое type tel html,
  2. Пример использования type tel.
  1. У поля ввода есть типы передаваемых данных 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 на сайте.

    HTML :

    Кроме поле ввода , мы можем добавит вовнутрь подсказку 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.

  2. Пример использования 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>

    Php :

    if($_POST[‘phone_submit’]) { $result = ‘Вы нажали кнопку отправить submit, переданное значение : ‘.strip_tags($_POST[‘phone’]) ;}

    echo $result;

    Результат:

    Введите номер телефона по шаблону, либо не по шаблону type tel и нажмите отправить:

Можете не благодарить, лучше помогите!

COMMENTS+

 
BBcode


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

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

Когда дело доходит до валидации пользовательских данных, ее можно проводить как на стороне клиента (в веб-браузере), так и на серверной стороне.

Ранее валидацию на стороне клиента можно было провести только с помощью JavaScript. Но все изменилось (или почти изменилось), так как с помощью HTML5 валидацию можно проводить средствами браузера, без необходимости писать сложные скрипты для валидации на JavaScript.

Валидация форм с помощью HTML5

HTML5 предоставляет довольно надежный механизм, основанный на следующих атрибутах тега <input />typepatternи require. Благодаря этим новым атрибутам вы можете переложить некоторые функции проверки данных на плечи браузера.

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

Атрибут type

Этот атрибут говорит, какое поле ввода отобразить для обработки данных, например, уже знакомое поле типа <input type="text" />

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

Попробуйте поиграться со значениями поля email в нижеприведенной демонстрации.

Также существуют другие стандартные типы полей, вроде <input type="number" /><input type="url" /> и <input type="tel" /> для валидации чисел, URL’ов и телефонных номеров соотвествено.

Замечание: формат телефонного номера различается для разных стран из-за несоответствия количества цифр в телефонных номерах и разности форматов. Как результат, спецификация не определяет алгоритм проверки телефонных номеров, так что на время написания статьи данная возможность слабо поддерживается браузерами.

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

Атрибут pattern

Атрибут pattern, скорее всего, заставит многих фронтенд-разработчиков прыгать от радости. Этот атрибут принимает регулярное выражение (аналогичное формату регулярных выражений JavaScript), по которому будет проверяться корректность введенных в поле данных.

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

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

Регулярные выражения (RegEX) являются мощным, кратким и гибким инструментом для сопоставления строки текста, вроде отдельных символов, слов или шаблонов символов.

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

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

Телефонные номера

Как упоминалось ранее, тип поля tel не полностью поддерживается браузерами из-за несоответствия форматов номеров телефонов в разных странах.

Например, в некоторых странах формат телефонных номеров представляется в виде xxxx-xxx-xxxx, и сам телефонный номер будет что-то вроде этого: 0803-555-8205.

Регулярное выражение, которому соответствует данный шаблон, такое: ^d{4}-d{3}-d{4}$. В коде это можно записатьтак:

<label for="phonenum">Phone Number:</label>
<input type="tel" pattern="^d{4}-d{3}-d{4}$" >

Буквенно-цифровые значения

Следующий шаблон соответствует набору буквенно-цифровых значений (комбинации букв английского алфавита и цифр):

<input type="text" pattern="[a-zA-Z0-9]+" >

Имя пользователя в Twitter

Данное регулярное выражение соответствует имени пользователя в твиттере, с предваряющим символом @, например@tech4sky:

<input type="text" pattern="^@[A-Za-z0-9_]{1,15}$" >

Цвет в шестнадцатеричном виде

Эта регулярка соответствует цвету в шестнадцатеричном виде, например #3b5998 или #000:

<input type="text" pattern="^#+([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$" >

Подсказки

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

<input type="text" name="ssn"
       pattern="^d{3}-d{2}-d{4}$"
       title="Номер Социального Страхования" />

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

Атрибут required

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

Это избавляет нас от реализации проверки полей с помощью JavaScript, что может сохранить немного времени разработчикам.

Например: <input type="text" name="my_name" required /> или <input type="text" name="my_name" required="required" />(для совместимости с XHTML)

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

Заключение

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

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

Не все браузеры поддерживают HTML5, и не все данные, посланные вашему скрипту, придут с вашей формы. Это значит, что перед тем, как окончательно принять данные от пользователя, необходимо проверить их корректность на стороне сервера.

Как мы уже говорили ранее,довольно сложно предоставить универсальное решение для проверки телефонных номеров на стороне клиента.Так что же мы можем сделать? Давайте рассмотрим некоторые варианты.

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

Вы можете сделать так, чтобы пустой ввод был недействительным и не передавался на сервер с использованием required атрибута. Например, воспользуемся этим 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>

И давайте включим следующую CSS,чтобы выделить действительные записи с галочкой и недействительные записи с крестиком:

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;
}

Выход выглядит так:

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

В этом примере мы будем использовать тот же CSS,что и раньше,но наш HTML изменен,чтобы выглядеть так:

<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>

Обратите внимание,что введенное значение считается недействительным,если не совпадает с шаблоном xxx-xxx-xxx;например,41-323-421 не будет принято.Также не будет принят номер 800-MDN-ROCKS.Однако 865-555-6502 будет принят.Этот конкретный шаблон,очевидно,полезен только для определенных локалей-в реальном приложении вам,вероятно,придется варьировать используемый шаблон в зависимости от локали пользователя.

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

Каждый ввод имеет атрибут- placeholder , чтобы показать зрячим пользователям подсказку о том, что в него вводить, pattern для принудительного ввода определенного количества символов для нужного раздела и атрибут aria-label , содержащий подсказку, которую нужно прочитать на экране. читатели пользователи о том, что в него входить.

<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>

JavaScript относительно прост — он содержит обработчик события onchange , который при изменении значения <select> обновляет pattern элемента <input> , placeholder и метку aria-label в соответствии с форматом телефонных номеров в этой стране/территории. pattern placeholder aria-label

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");
  }
}

Пример выглядит так:

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

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

Понравилась статья? Поделить с друзьями:
  • Паттайя номер телефона
  • Патрушево морг номера телефонов
  • Патрушево кардиология номер телефона регистратуры
  • Патронный завод ульяновск номер телефона
  • Патриот уссурийск каток номер телефона