HTMLObjectElement.setCustomValidity

The setCustomValidity() method of the HTMLObjectElement interface sets a custom validity message for the element.

Syntax

HTMLObjectElement.setCustomValidity(message);

Parameters

error
The message to use for validity errors.

Return value

undefined

Exceptions

None.

Examples

In this example, we pass the ID of an input element, and set different error messages depending on whether the value is missing, too low or too high.

function validate(inputID) {
  var input = document.getElementById(inputID);
  var validityState_object = input.validity;
  if(validityState_object.valueMissing) {
     input.setCustomValidity('You gotta fill this out, yo!');
  } else if (input.rangeUnderflow) {
    input.setCustomValidity('We need a higher number!');
  } else if (input.rangeOverflow) {
    input.setCustomValidity('Thats too high!');
  } else {
    input.setCustomValidity('');
  }
}

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

Specifications

Specification Status Comment
HTML Living Standard
The definition of 'setCustomValidity' in that specification.
Living Standard Initial definition.

Browser compatibility

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
setCustomValidityChrome Full support YesEdge Full support 12Firefox Full support 1IE Full support YesOpera Full support YesSafari Full support 6WebView Android Full support YesChrome Android Full support YesFirefox Android Full support 4Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android ?

Legend

Full support Ā 
Full support
Compatibility unknown Ā 
Compatibility unknown

See also