Атрибут pattern

Примеры шаблонов для использования в input pattern

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

 
95[\)]\s?\d[-]\d[-]\d" placeholder="+7(___)___-__-__">

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

Введите дату в формате дд.мм.гггг:

\.4\.4">

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

Источник

HTML attribute: pattern

The pattern attribute specifies a regular expression the form control’s value should match. If a non- null value doesn’t conform to the constraints set by the pattern value, the ValidityState object’s read-only patternMismatch property will be true.

Try it

Overview

The pattern attribute is an attribute of the text, tel, email, url, password, and search input types.

The pattern attribute, when specified, is a regular expression which the input’s value must match 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.

Читайте также:  One hot encoding питон

If the specified pattern is not specified or is invalid, no regular expression is applied and this attribute is ignored.

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 must not rely on the tooltip alone for an explanation. See below for more information on usability.

Some of the input types supporting the pattern attribute, notably the email and url input types, have expected value syntaxes that must be matched. If the pattern attribute isn’t present, and the value doesn’t match the expected syntax for that value type, the ValidityState object’s read-only typeMismatch property will be true.

Usability

When including a pattern , provide a description of the pattern in visible text near the control. Additionally, include a title attribute which gives a description of the pattern. User agents may use the title contents during constraint validation to tell the user that the pattern is not matched. Some browsers show a tooltip with title contents, improving usability for sighted users. Additionally, assistive technology may read the title aloud when the control gains focus, but this should not be relied upon for accessibility.

Constraint validation

If the input’s value is not the empty string and the value does not match the entire regular expression, there is a constraint violation reported by the ValidityState object’s patternMismatch property being true . The pattern’s regular expression, when matched against the value, must have its start anchored to the start of the string and its end anchored to the end of the string, which is slightly different from JavaScript regular expressions: in the case of pattern attribute, we are matching against the entire value, not just any subset, as if a ^(?: were implied at the start of the pattern and )$ at the end.

Note: If the pattern attribute is specified with no value, its value is implicitly the empty string. Thus, any non-empty input value will result in constraint violation.

Examples

Matching a phone number

p> label> Enter your phone number in the format (123) - 456 - 7890 (input name="tel1" type="tel" pattern="6" placeholder="###" aria-label="3-digit area code" size="2" />) - input name="tel2" type="tel" pattern="5" placeholder="###" aria-label="3-digit prefix" size="2" /> - input name="tel3" type="tel" pattern="2" placeholder="####" aria-label="4-digit number" size="3" /> label> p> 

Here we have 3 sections for a north American phone number with an implicit label encompassing all three components of the phone number, expecting 3-digits, 3-digits and 4-digits respectively, as defined by the pattern attribute set on each.

If the values are too long or too short, or contain characters that aren’t digits, the patternMismatch will be true. When true , the element matches the :invalid CSS pseudo-classes.

input:invalid  border: red solid 3px; > 

If we had used minlength and maxlength attributes instead, we may have seen validityState.tooLong or validityState.tooShort being true.

Specifying a pattern

You can use the pattern attribute to specify a regular expression that the inputted value must match in order to be considered valid (see Validating against a regular expression for a simple crash course on using regular expressions to validate inputs).

The example below restricts the value to 4-8 characters and requires that it contain only lower-case letters.

form> div> label for="uname">Choose a username: label> input type="text" id="uname" name="name" required size="45" pattern="[a-z]" title="4 to 8 lowercase letters" /> span class="validity">span> p>Usernames must be lowercase and 4-8 characters in length.p> div> div> button>Submitbutton> div> form> 
div  margin-bottom: 10px; position: relative; > p  font-size: 80%; color: #999; > input + span  padding-right: 30px; > input:invalid + span::after  position: absolute; content: "✖"; padding-left: 5px; > input:valid + span::after  position: absolute; content: "✓"; padding-left: 5px; > 

Accessibility Concerns

When a control has a pattern attribute, the title attribute, if used, must describe the pattern. Relying on the title attribute for the visual display of text content is generally discouraged as many user agents do not expose the attribute in an accessible manner. Some browsers show a tooltip when an element with a title is hovered, but that leaves out keyboard-only and touch-only users. This is one of the several reasons you must include information informing users how to fill out the control to match the requirements.

While title s are used by some browsers to populate error messaging, because browsers sometimes also show the title as text on hover, it therefore shows in non-error situations, so be careful not to word titles as if an error has occurred.

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Источник

Атрибут pattern

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

Синтаксис

Значения

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

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

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

Введите телефон в формате 2-xxx-xxx, где вместо x должна быть цифра:

-7">

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

Источник

Allow only numbers to enter in the HTML input – Javascript

Allow only digits to enter in the html input

For other solutions we have to use JavaScript. That means no one can input invalid values; it will allow only numbers to enter in the HTML input.

JavaScript solutions to allow only numbers

Step 1.

Create a function where we will pass the two parameters one will be input field and another will be callback function.

This function will include all the possible events on the input field and add the JavaScript listeners for them.

This is a one time process, after this, this method will take care of everything.

function setInputFilter(textbox, inputFilter) < ["input", "keydown", "keyup", "mousedown", "mouseup", "select", "contextmenu", "drop"].forEach(function(event) < textbox.addEventListener(event, function() < if (inputFilter(this.value)) < this.oldValue = this.value; this.oldSelectionStart = this.selectionStart; this.oldSelectionEnd = this.selectionEnd; >else if (this.hasOwnProperty("oldValue")) < this.value = this.oldValue; this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd); >else < this.value = ""; >>); >); >

Step 2.

Now just setup the input filter for your input field. We can use this filter as many times as we want.

setInputFilter(document.getElementById("numbersOnly"), function(value) < return /^\d*\.?\d*$/.test(value); >);

It is using regular Expression to allow only numbers and dots to enter in the HTML input.

Inline JavaScript to make simpler solution

Inline Js with regular Expression

We can use the oninput attribute of HTML input to listen to the changes of the field value. As the onchange event needs focus out of the input field to trigger, oninput can detect the changes while typing the data into it.

Some jQuery solutions

Let’s see some basic and useful jQuery solutions to allow only digits to enter in the HTML input field. Best point is you don’t need to remember regular Expression pattern here. We are going to use the isNaN() function to identify non-numeric values.

$('body').on('propertychange input', 'input[type="text"]', function() < var inputVal = $(this).val(); if( isNaN(Number(inputVal)) ) < this.value = this.hasOwnProperty("oldValue") ? this.oldValue : ''; >else < this.oldValue = inputVal; >>);

It can prevent copying non-numeric values to the input field. Allow for single decimal point and also control the drag and drop non-numeric content to this input field.

Hope you find this article useful. Please share your opinion in the comment section below.

If you have learned any other method to achieve the same, do comment below. I will add that to this list.

Let’s Learn together and grow together.

Источник

Оцените статью