Тег INPUT, атрибут maxlength

Атрибуты minlength и maxlength

Атрибуты minlength и maxlength устанавливают полям ввода минимальное и максимальное количество символов.

Время чтения: меньше 5 мин

Это незавершённая статья. Вы можете помочь её закончить! Почитайте о том, как контрибьютить в Доку.

Кратко

Скопировать ссылку «Кратко» Скопировано

Атрибуты minlength и maxlength позволяют устанавливать минимальное и максимальное количество символов в полях ввода или .

Как пишется

Скопировать ссылку «Как пишется» Скопировано

  input minlength="4" maxlength="8"> textarea minlength="50" maxlength="1000">      

Пример

Скопировать ссылку "Пример" Скопировано

Создадим поле для ввода пароля и ограничим количество допустимых символов:

   type="password" name="password" required minlength="8" maxlength="16"> label for="password">Введите пароль (от 8 до 16 символов):label> input type="password" id="password" name="password" required minlength="8" maxlength="16" >      

Как понять

Скопировать ссылку "Как понять" Скопировано

Атрибуты minlength и maxlength устанавливают минимальное и максимальное количество символов в полях ввода или . Значением атрибутов должно быть целое число от 0 и выше. Если значение атрибутов не указано, или указано неправильно, ограничений по длине у поля не будет.

При добавлении полю обоих атрибутов, значение minlength всегда должно быть меньше значения maxlength . Если за этим не уследить, то поле всегда будет невалидным.

Источник

HTML maxlength Attribute

An element with a maximum length of 10 characters:

Definition and Usage

The maxlength attribute specifies the maximum number of characters allowed in the element.

Browser Support

The numbers in the table specify the first browser version that fully supports the attribute.

Attribute
maxlength Yes Yes Yes Yes Yes

Syntax

Attribute Values

Value Description
number The maximum number of characters allowed in the element. Default value is 524288

❮ HTML tag

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

HTML Input Attributes

This chapter describes the different attributes for the HTML element.

The value Attribute

The input value attribute specifies an initial value for an input field:

Example

Input fields with initial (default) values:

The readonly Attribute

The input readonly attribute specifies that an input field is read-only.

A read-only input field cannot be modified (however, a user can tab to it, highlight it, and copy the text from it).

The value of a read-only input field will be sent when submitting the form!

Example

The disabled Attribute

The input disabled attribute specifies that an input field should be disabled.

A disabled input field is unusable and un-clickable.

The value of a disabled input field will not be sent when submitting the form!

Example

The size Attribute

The input size attribute specifies the visible width, in characters, of an input field.

The default value for size is 20.

Note: The size attribute works with the following input types: text, search, tel, url, email, and password.

Example

Set a width for an input field:

The maxlength Attribute

The input maxlength attribute specifies the maximum number of characters allowed in an input field.

Note: When a maxlength is set, the input field will not accept more than the specified number of characters. However, this attribute does not provide any feedback. So, if you want to alert the user, you must write JavaScript code.

Example

Set a maximum length for an input field:

The min and max Attributes

The input min and max attributes specify the minimum and maximum values for an input field.

The min and max attributes work with the following input types: number, range, date, datetime-local, month, time and week.

Tip: Use the max and min attributes together to create a range of legal values.

Example

Set a max date, a min date, and a range of legal values:

The multiple Attribute

The input multiple attribute specifies that the user is allowed to enter more than one value in an input field.

The multiple attribute works with the following input types: email, and file.

Example

A file upload field that accepts multiple values:

The pattern Attribute

The input pattern attribute specifies a regular expression that the input field's value is checked against, when the form is submitted.

The pattern attribute works with the following input types: text, date, search, url, tel, email, and password.

Tip: Use the global title attribute to describe the pattern to help the user.

Tip: Learn more about regular expressions in our JavaScript tutorial.

Example

An input field that can contain only three letters (no numbers or special characters):

The placeholder Attribute

The input placeholder attribute specifies a short hint that describes the expected value of an input field (a sample value or a short description of the expected format).

The short hint is displayed in the input field before the user enters a value.

The placeholder attribute works with the following input types: text, search, url, tel, email, and password.

Example

An input field with a placeholder text:

The required Attribute

The input required attribute specifies that an input field must be filled out before submitting the form.

The required attribute works with the following input types: text, search, url, tel, email, password, date pickers, number, checkbox, radio, and file.

Example

The step Attribute

The input step attribute specifies the legal number intervals for an input field.

Example: if step="3", legal numbers could be -3, 0, 3, 6, etc.

Tip: This attribute can be used together with the max and min attributes to create a range of legal values.

The step attribute works with the following input types: number, range, date, datetime-local, month, time and week.

Example

An input field with a specified legal number intervals:

Note: Input restrictions are not foolproof, and JavaScript provides many ways to add illegal input. To safely restrict input, it must also be checked by the receiver (the server)!

The autofocus Attribute

The input autofocus attribute specifies that an input field should automatically get focus when the page loads.

Example

Let the "First name" input field automatically get focus when the page loads:

The height and width Attributes

The input height and width attributes specify the height and width of an element.

Tip: Always specify both the height and width attributes for images. If height and width are set, the space required for the image is reserved when the page is loaded. Without these attributes, the browser does not know the size of the image, and cannot reserve the appropriate space to it. The effect will be that the page layout will change during loading (while the images load).

Example

Define an image as the submit button, with height and width attributes:

The list Attribute

The input list attribute refers to a element that contains pre-defined options for an element.

Example

An element with pre-defined values in a :

The autocomplete Attribute

The input autocomplete attribute specifies whether a form or an input field should have autocomplete on or off.

Autocomplete allows the browser to predict the value. When a user starts to type in a field, the browser should display options to fill in the field, based on earlier typed values.

The autocomplete attribute works with and the following types: text, search, url, tel, email, password, datepickers, range, and color.

Example

An HTML form with autocomplete on, and off for one input field:

Tip: In some browsers you may need to activate an autocomplete function for this to work (Look under "Preferences" in the browser's menu).

HTML Exercises

HTML Form and Input Elements

For a complete list of all available HTML tags, visit our HTML Tag Reference.

Источник

Атрибут maxlength

Устанавливает максимальное число символов, которое может быть введено пользователем в текстовом поле. Когда это количество достигается при наборе, дальнейший ввод становится невозможным.

Синтаксис

Значения

Любое целое положительное число.

Значение по умолчанию

Ввод символов не ограничен.

      

Не выкладывайте свой код напрямую в комментариях, он отображается некорректно. Воспользуйтесь сервисом cssdeck.com или jsfiddle.net, сохраните код и в комментариях дайте на него ссылку. Так и результат сразу увидят.

Типы тегов

HTML5

Блочные элементы

Строчные элементы

Универсальные элементы

Нестандартные теги

Осуждаемые теги

Видео

Документ

Звук

Изображения

Объекты

Скрипты

Списки

Ссылки

Таблицы

Текст

Форматирование

Формы

Фреймы

Источник

Читайте также:  METANIT.COM
Оцените статью