ValidityState: valid 屬性
ValidityState 介面的只讀屬性 valid 指示一個 ValidityState 物件的 <input> 元素的值是否滿足所有驗證約束,因此被認為是有效的。
值
如果 ValidityState 符合所有約束,則為 true,否則為 false。
示例
顯示有效性狀態
以下示例檢查一個 數字輸入元素 的有效性。使用 min 屬性添加了一個約束,該約束為輸入設定了最小值 18。如果使用者輸入的任何值不是大於 17 的數字,則該元素將無法透過約束驗證,並且將應用匹配 input:invalid 的樣式。
css
input:invalid {
outline: red solid 3px;
}
input:valid {
outline: palegreen solid 3px;
}
html
<pre id="log">Validation logged here...</pre>
<input type="number" id="age" min="18" required />
js
const userInput = document.getElementById("age");
const logElement = document.getElementById("log");
function log(text) {
logElement.innerText = text;
}
userInput.addEventListener("input", () => {
userInput.reportValidity();
if (userInput.validity.valid) {
log("Input OK…");
} else {
log("Bad input detected…");
}
});
規範
| 規範 |
|---|
| HTML # dom-validitystate-valid-dev |
瀏覽器相容性
載入中…
另見
- ValidityState badInput, customError 屬性。
- 約束驗證
- 表單:資料表單驗證