HTMLTextAreaElement: setCustomValidity() 方法

Baseline 已廣泛支援

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

setCustomValidity() 方法是 HTMLTextAreaElement 介面的一部分,用於設定 <textarea> 元素的自定義有效性訊息。使用空字串表示該元素沒有自定義有效性錯誤。

語法

js
setCustomValidity(string)

引數

string

包含錯誤訊息的字串。空字串會移除任何自定義有效性錯誤。

返回值

無(undefined)。

示例

在此示例中,如果 <textarea> 未透過約束驗證,我們將根據驗證失敗的約束提供自定義錯誤。如果值為有效,我們將自定義錯誤設定為一個空字串。

js
const comment = document.getElementById("comment");
if (comment.validity.valueMissing) {
  comment.setCustomValidity("We can't submit a blank comment!");
} else if (comment.validity.tooShort) {
  comment.setCustomValidity("Tell us more! Your comment is too short.");
} else if (comment.validity.tooLong) {
  comment.setCustomValidity(
    "Loquacious much? Keep it to under 800 characters!",
  );
} else {
  comment.setCustomValidity("");
}

規範

規範
HTML
# dom-cva-setcustomvalidity-dev

瀏覽器相容性

另見