HTMLOutputElement: setCustomValidity() 方法

Baseline 已廣泛支援

此功能已相當成熟,可在多種裝置和瀏覽器版本上執行。自 ⁨2016 年 8 月⁩ 起,所有瀏覽器均已提供此功能。

setCustomValidity() 方法屬於 HTMLOutputElement 介面,用於為 <output> 元素設定自定義的有效性訊息。使用空字串表示該元素沒有自定義有效性錯誤。

<output> 元素不是約束驗證的候選物件。reportValidity() 方法不會導致向用戶顯示自定義錯誤訊息,但會將其元素 ValidityState 物件的 customError 屬性設定為 true,並將 valid 屬性設定為 false

語法

js
setCustomValidity(string)

引數

string

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

返回值

無(undefined)。

示例

在此示例中,如果 <output>value 不是非零數字,我們會設定一個自定義錯誤訊息。如果它是一個數字,我們會將自定義錯誤設定為空字串。

js
const cart = document.getElementById("cart-form");
const total = cart.elements("total");
if (parseFloat(total.value)) {
  errorOutput.setCustomValidity("");
} else {
  errorOutput.setCustomValidity("There is an error");
}

規範

規範
HTML
# dom-cva-setcustomvalidity-dev

瀏覽器相容性

另見