HTML 屬性:maxlength
maxlength 屬性定義了使用者可以在 <input> 或 <textarea> 中輸入的字串的最大 長度。該屬性必須是 0 或更高的整數值。
長度以 UTF-16 碼單元為單位進行度量,這通常(但不總是)等於字元數。如果未指定 maxlength,或者指定了無效值,則輸入沒有最大長度。
如果存在並且有效的 minlength 屬性,則任何 maxlength 值都必須大於或等於 minlength 的值。如果欄位的文字值長度超過 maxlength UTF-16 碼單元,則輸入將無法透過約束驗證。約束驗證僅在值由使用者更改時應用。
約束驗證
雖然瀏覽器通常會阻止使用者輸入超出 maxlength 屬性允許範圍的文字,但如果長度超過 maxlength 允許的長度,則 tooLong 屬性(ValidityState 物件的一個只讀屬性)將為 true。
試一試
<label for="name">Product name:</label>
<input
id="name"
name="name"
type="text"
value="Shampoo"
minlength="3"
maxlength="20"
required />
<label for="description">Product description:</label>
<textarea
id="description"
name="description"
minlength="10"
maxlength="40"
required></textarea>
label {
display: block;
margin-top: 1em;
}
input:valid,
textarea:valid {
background-color: palegreen;
}
示例
html
<input type="password" maxlength="4" />
規範
| 規範 |
|---|
| HTML # attr-input-maxlength |
| HTML # attr-textarea-maxlength |
瀏覽器相容性
html.elements.input.maxlength
載入中…
html.elements.textarea.maxlength
載入中…