The HTMLInputElement.setCustomValidity()
method sets a custom validity message for the element.
On this page
HTMLInputElement: setCustomValidity() method
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 error messages depending on whether the value is missing, too low, or too high. Additionally you must call the reportValidity()
method on the same element or else nothing will happen.
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 the error message is not empty, the form will not pass validation and will not be submitted.
Specifications
Specification |
---|
HTML Standard # dom-cva-setcustomvalidity-dev |
Browser compatibility
Desktop | Mobile | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | |
setCustomValidity |
10 | 12 | 4 | 10 | ≤12.1 | 5.1 | ≤37 | 18 | 4 | ≤12.1 | 5 | 1.0 |
See also
© 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setCustomValidity