HTMLInputElement: setCustomValidity() メソッド
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since December 2018.
HTMLInputElement.setCustomValidity()
メソッドは、その要素にカスタム検証メッセージを設定します。
構文
js
setCustomValidity(message)
引数
message
-
検証エラーに使用するメッセージです。
返値
なし (undefined
)。
例外
なし。
例
この例では、 input 要素の 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("That's too high!");
} else {
input.setCustomValidity("");
}
input.reportValidity();
}
エラーがない場合は、メッセージを空文字列に設定することが重要です。エラーメッセージが空でない限り、フォームは検証を通過せず、送信されません。
仕様書
Specification |
---|
HTML # dom-cva-setcustomvalidity |
ブラウザーの互換性
Report problems with this compatibility data on GitHubdesktop | mobile | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
setCustomValidity |
Legend
Tip: you can click/tap on a cell for more information.
- Full support
- Full support
- See implementation notes.
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.