ValidityState: valueMissing 屬性
ValidityState 介面的只讀 valueMissing 屬性指示一個 required 控制元件,例如 <input>、<select> 或 <textarea>,是否具有空值。
如果設定了 required 屬性,並且未選擇 <option>,或者 <textarea> 或使用者可編輯的 <input> 為空,則 valueMissing 屬性將為 true。僅當欄位是必需的且沒有值時,該屬性才為 true;如果欄位不是必需的,或者欄位是必需的但有值,則該值為 false。
值
如果 ValidityState 未設定且 required 屬性已設定,則此布林值為 true。
缺少必需的輸入值
以下示例檢查 數字輸入元素 的有效性。透過 min 屬性 添加了約束,該屬性將輸入的最小值設定為 18,並透過 required 屬性 禁止空值。如果使用者輸入的任何值不是大於 17 的數字,則該元素將驗證失敗,並應用與 :invalid 匹配的樣式。
css
input:invalid {
outline: red 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 if (userInput.validity.valueMissing) {
log("Required field cannot be empty.");
} else {
log(`Bad input detected: ${userInput.validationMessage}`);
}
});
規範
| 規範 |
|---|
| HTML # dom-validitystate-valuemissing-dev |
瀏覽器相容性
載入中…