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 GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
setCustomValidity

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
See implementation notes.

関連情報