ValidityState: customError property
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.
The read-only customError
property of the ValidityState
interface returns true
if an element doesn't meet the validation required in the custom validity set by the element's setCustomValidity()
method.
Value
A boolean that is true
if a custom error message has been set to a non-empty string.
Examples
Detecting a custom error
In this example, setCustomValidity()
sets a custom error message when a form submission contains user input that's considered invalid.
The "Validate input" button calls reportValidity()
, which displays a validation message under the element if a user enters values that do not match the form's constraints.
If you enter the text "good" or "fine" and try to validate the input, the field is marked invalid until the custom error message is cleared (set to an empty string).
For comparison, there is a minlength
attribute on the input element that allows us to demonstrate the tooShort
validity state when the user enters less than two characters.
When the value in the form control is invalid, even if there is no custom error, the input will have a red outline.
HTML
<pre id="log">Validation failures logged here...</pre>
<input
type="text"
id="userInput"
placeholder="How do you feel?"
minlength="2" />
<button id="checkButton">Validate input</button>
CSS
input:invalid {
border: red solid 3px;
}
JavaScript
const userInput = document.getElementById("userInput");
const checkButton = document.getElementById("checkButton");
const logElement = document.getElementById("log");
function log(text) {
logElement.innerText = text;
}
const check = (input) => {
// Handle cases where input is too vague
if (input.value == "good" || input.value == "fine") {
input.setCustomValidity(`"${input.value}" is not a feeling.`);
} else {
// An empty string resets the custom validity state
input.setCustomValidity("");
}
};
userInput.addEventListener("input", () => {
check(userInput);
});
const validateInput = () => {
userInput.reportValidity();
if (userInput.validity.customError) {
// We can handle custom validity states here
log("Custom validity error: " + userInput.validationMessage);
} else {
log(userInput.validationMessage);
}
};
checkButton.addEventListener("click", validateInput);
Result
Specifications
Specification |
---|
HTML Standard # dom-validitystate-customerror-dev |
Browser compatibility
BCD tables only load in the browser
See also
- ValidityState badInput, valid properties.
- Constraint validation
- Forms: Data form validation