Movatterモバイル変換


[0]ホーム

URL:


  1. Web
  2. Web APIs
  3. HTMLInputElement
  4. setCustomValidity()

HTMLInputElement: setCustomValidity() method

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since ⁨July 2015⁩.

TheHTMLInputElement.setCustomValidity() method sets a custom validity message for the element.

Syntax

js
setCustomValidity(message)

Parameters

message

The message to use for validity errors.

Return value

None (undefined).

Exceptions

None.

Examples

In this example, we pass the ID of an input element and set different errormessages depending on whether the value is missing, too low, or too high. Notethat the message will not be displayed immediately. Attempting to submit theform will display the message, or you can call thereportValidity() methodon the element.

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();}

It's vital to set the message to an empty string if there are no errors. As long as theerror message is not empty, the form will not pass validation and will not besubmitted.

Specifications

Specification
HTML
# dom-cva-setcustomvalidity

Browser compatibility

See also

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp