ValidityState: customError 屬性

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

ValidityState 介面的只讀 customError 屬性會在元素不符合透過元素 setCustomValidity() 方法設定的自定義有效性要求時返回 true

如果已將自定義錯誤訊息設定為非空字串,則返回 true

示例

檢測自定義錯誤

在此示例中,當表單提交包含被視為無效的使用者輸入時,setCustomValidity() 會設定自定義錯誤訊息。“驗證輸入”按鈕呼叫 reportValidity(),當用戶輸入的值不符合 表單的約束 時,它會在元素下方顯示驗證訊息。

如果您輸入文字“good”或“fine”並嘗試驗證輸入,則在清除自定義錯誤訊息(設定為空字串)之前,該欄位將被標記為無效。作為比較,輸入元素上有一個 minlength 屬性,允許我們在使用者輸入的字元少於兩個時演示 tooShort 有效性狀態。當表單控制元件中的值無效時,即使沒有自定義錯誤,輸入也會有一個紅色的輪廓。

HTML

html
<pre id="log">Validation failures logged here...</pre>
<input
  type="text"
  id="userInput"
  placeholder="How do you feel?"
  minlength="2" />
<button id="checkButton">Validate input</button>

CSS

css
input:invalid {
  border: red solid 3px;
}

JavaScript

js
const userInput = document.getElementById("userInput");
const checkButton = document.getElementById("checkButton");
const logElement = document.getElementById("log");

function log(text) {
  logElement.innerText = text;
}

const check = (input) => {
  // Handle cases where input is too vague
  if (input.value === "good" || input.value === "fine") {
    input.setCustomValidity(`"${input.value}" is not a feeling.`);
  } else {
    // An empty string resets the custom validity state
    input.setCustomValidity("");
  }
};

userInput.addEventListener("input", () => {
  check(userInput);
});

const validateInput = () => {
  userInput.reportValidity();
  if (userInput.validity.customError) {
    // We can handle custom validity states here
    log(`Custom validity error: ${userInput.validationMessage}`);
  } else {
    log(userInput.validationMessage);
  }
};

checkButton.addEventListener("click", validateInput);

結果

規範

規範
HTML
# dom-validitystate-customerror-dev

瀏覽器相容性

另見