ValidityState: tooShort 屬性
ValidityState 介面的只讀 tooShort 屬性指示 ValidityState 介面的只讀 tooShort 屬性表示,經過使用者編輯後,<input>、<button>、<select>、<output>、<fieldset> 或 <textarea> 元素的值是否小於元素 minlength 屬性設定的最小程式碼單元長度。
值
如果 ValidityState 不符合約束,則為 true 的布林值。
示例
輸入值過短
下面的示例檢查一個 文字輸入元素 的有效性。使用 minlength 屬性 添加了一個約束,因此輸入需要至少包含 4 個字元。如果使用者輸入的字串太短,該元素將驗證失敗,並應用與 :invalid CSS 偽類匹配的樣式。
css
input:invalid {
outline: red solid 3px;
}
html
<pre id="log">Validation logged here...</pre>
<input type="text" id="userText" minlength="4" />
js
const userInput = document.getElementById("userText");
const logElement = document.getElementById("log");
function log(text) {
logElement.innerText = text;
}
userInput.addEventListener("input", () => {
userInput.reportValidity();
if (userInput.validity.tooShort) {
log("Not enough characters entered.");
} else {
log("Input is valid…");
}
});
規範
| 規範 |
|---|
| HTML # dom-validitystate-tooshort-dev |
瀏覽器相容性
載入中…