ValidityState: badInput 屬性

Baseline 已廣泛支援

此功能已成熟,並可在許多裝置和瀏覽器版本上執行。自 2018 年 12 月起,所有瀏覽器均支援此功能。

ValidityState 介面中只讀的 badInput 屬性指示使用者輸入了瀏覽器無法轉換的內容。例如,如果有一個數字輸入框,其內容是字串。

一個布林值,如果 ValidityState 物件不符合預期型別,則為 true

示例

檢測無效輸入

下面的示例檢查一個 數字輸入框 的有效性。如果使用者輸入的是文字而不是數字,該元素將無法透過約束驗證,並且會應用與 input:invalid 匹配的樣式。當元素的 badInput 求值為 true 時,輸入框上方的 <pre> 元素會顯示驗證訊息。

css
input:invalid {
  outline: red solid 3px;
}
html
<pre id="log">Validation logged here...</pre>
<input type="number" id="age" />
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.badInput) {
    log(`Bad input detected: ${userInput.validationMessage}`);
  }
});

規範

規範
HTML
# dom-validitystate-badinput-dev

瀏覽器相容性

另見