HTMLObjectElement: setCustomValidity() 方法
HTMLObjectElement 介面的 setCustomValidity() 方法用於為元素設定自定義有效性訊息。
語法
js
setCustomValidity(errorMessage)
引數
errorMessage-
用於有效性錯誤的的訊息。
返回值
無(undefined)。
異常
無。
示例
在此示例中,我們傳遞一個輸入元素的 ID,並根據值是否缺失、過低或過高來設定不同的錯誤訊息。請注意,訊息不會立即顯示。嘗試提交表單時會顯示訊息,或者您可以呼叫元素上的 reportValidity() 方法。
js
function validate(inputID) {
const input = document.getElementById(inputID);
const validityState = input.validity;
if (validityState.valueMissing) {
input.setCustomValidity("You gotta fill this out, yo!");
} else if (validityState.rangeUnderflow) {
input.setCustomValidity("We need a higher number!");
} else if (validityState.rangeOverflow) {
input.setCustomValidity("Thats too high!");
} else {
input.setCustomValidity("");
}
input.reportValidity();
}
如果不存在錯誤,則必須將訊息設定為空字串。只要錯誤訊息不為空,表單將無法透過驗證且不會被提交。
規範
| 規範 |
|---|
| HTML # dom-cva-setcustomvalidity-dev |
瀏覽器相容性
載入中…