HTML 属性:maxlength

maxlength 属性定义用户可以输入 <input><textarea> 的最大 字符串长度。该属性必须具有 0 或更大的整数值。

¥The maxlength attribute defines the maximum string length that the user can enter into an <input> or <textarea>. The attribute must have an integer value of 0 or higher.

长度以 UTF-16 代码单元测量,其中 (对于大多数脚本) 相当于字符数。如果未指定 maxlength,或者指定了无效值,则输入没有最大长度。

¥The length is measured in UTF-16 code units, which (for most scripts) is equivalent to the number of characters. If no maxlength is specified, or an invalid value is specified, the input has no maximum length.

任何 maxlength 值都必须大于或等于 minlength 的值(如果存在且有效)。如果字段文本值的长度大于 maxlength UTF-16 代码单元长度,则输入将无法通过约束验证。仅当用户更改值时才应用约束验证。

¥Any maxlength value must be greater than or equal to the value of minlength, if present and valid. The input will fail constraint validation if the length of the text value of the field is greater than maxlength UTF-16 code units long. Constraint validation is only applied when the value is changed by the user.

约束验证

¥Constraint validation

虽然浏览器通常会阻止用户输入超过 maxlength 属性允许的文本,但如果长度超过 maxlength 允许的长度,则 ValidityState 对象的只读 tooLong 属性将为 true。

¥While the browser will generally prevent user from entering more text than the maxlength attribute allows, should the length be longer than the maxlength allows, the read-only tooLong property of a ValidityState object will be true.

Try it

示例

¥Examples

html
<input type="password" maxlength="4" />

规范

Specification
HTML Standard
# attr-input-maxlength
HTML Standard
# attr-textarea-maxlength

¥Specifications

浏览器兼容性

¥Browser compatibility

html.elements.input.maxlength

BCD tables only load in the browser

html.elements.textarea.maxlength

BCD tables only load in the browser

也可以看看