This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
The setCustomValidity() method of the HTMLObjectElement interface sets a custom validity message for the element.
setCustomValidity(errorMessage)
errorMessageThe message to use for validity errors.
None (undefined).
None.
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. Note that the message will not be displayed immediately. Attempting to submit the form will display the message, or you can call the reportValidity() method on the element.
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();
}
It's vital to set the message to an empty string if there are no errors. As long as the error message is not empty, the form will not pass validation and will not be submitted.
| Specification |
|---|
| HTML> # dom-cva-setcustomvalidity-dev> |
| Desktop | Mobile | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Chrome | Edge | Firefox | Opera | Safari | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | WebView Android | WebView on iOS | |
setCustomValidity |
10This method only updates the validation error popup, not the tooltip that appears when hovering the mouse over the element, see bug 41380670. |
12 | 4 | ≤12.1 | 5.1 | 18This method only updates the validation error popup, not the tooltip that appears when hovering the mouse over the element, see bug 41380670. |
4 | ≤12.1 | 5 | 1.0This method only updates the validation error popup, not the tooltip that appears when hovering the mouse over the element, see bug 41380670. |
4.4This method only updates the validation error popup, not the tooltip that appears when hovering the mouse over the element, see bug 41380670. |
5 |
validityStatevalidityState.valueMissingvalidityState.typeMismatchvalidityState.patternMismatchvalidityState.tooLongvalidityState.tooShortvalidityState.rangeUnderflowvalidityState.rangeOverflowvalidityState.stepMismatchvalidityState.validvalidityState.customError
© 2005–2025 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/HTMLObjectElement/setCustomValidity