HTML 属性:minlength

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

¥The minlength attribute defines the minimum 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 代码单元测量,其中 (对于大多数脚本) 相当于字符数。如果未指定 minlength,或指定了无效值,则输入没有最小长度。该值必须小于或等于 maxlength 的值,否则该值将永远无效,因为不可能同时满足这两个条件。

¥The length is measured in UTF-16 code units, which (for most scripts) is equivalent to the number of characters. If no minlength is specified, or an invalid value is specified, the input has no minimum length. This value must be less than or equal to the value of maxlength, otherwise the value will never be valid, as it is impossible to meet both criteria.

如果字段的文本值的长度小于 minlength UTF-16 代码单元长度,则输入将失败约束验证,并且 validityState.tooShort 返回 true。仅当用户更改值时才应用约束验证。一旦提交失败,某些浏览器会显示一条错误消息,指示所需的最小长度和当前长度。

¥The input will fail constraint validation if the length of the text value of the field is less than minlength UTF-16 code units long, with validityState.tooShort returning true. Constraint validation is only applied when the value is changed by the user. Once submission fails, some browsers will display an error message indicating the minimum length required and the current length.

Try it

示例

¥Examples

通过添加 minlength="5",该值必须为空或五个字符或更长才有效。

¥By adding minlength="5", the value must either be empty or five characters or longer to be valid.

html
<label for="fruit">Enter a fruit name that is at least 5 letters long</label>
<input type="text" minlength="5" id="fruit" />

我们可以使用伪类根据值是否有效来设置元素的样式。只要该值是 null(空)或五个或更多字符长,该值就有效。酸橙无效,柠檬有效。

¥We can use pseudoclasses to style the element based on whether the value is valid. The value will be valid as long as it is either null (empty) or five or more characters long. Lime is invalid, lemon is valid.

css
input {
  border: 2px solid currentcolor;
}
input:invalid {
  border: 2px dashed red;
}
input:invalid:focus {
  background-image: linear-gradient(pink, lightgreen);
}

规范

Specification
HTML Standard
# attr-input-minlength
HTML Standard
# the-maxlength-and-minlength-attributes

¥Specifications

浏览器兼容性

¥Browser compatibility

html.elements.input.minlength

BCD tables only load in the browser

html.elements.textarea.minlength

BCD tables only load in the browser

也可以看看