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
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 nothing will happen.
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!');
input.reportValidity();
}
else if (validityState_object.rangeUnderflow)
{
input.setCustomValidity('We need a higher number!');
input.reportValidity();
}
else if (validityState_object.rangeOverflow)
{
input.setCustomValidity('Thats too high!');
input.reportValidity();
}
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 null, the form will not pass validation and will not be submitted.
Specifications
Specification | Status | Comment |
HTML Living StandardThe definition of 'setCustomValidity' in that specification. | Living Standard | Initial definition. |
Browser compatibility
The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.
Update compatibility data on GitHub
Desktop | Mobile | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
setCustomValidity
|
Chrome
Full support 10 |
Edge
Full support 12 |
Firefox
Full support 1 |
IE
Full support 10 |
Opera
Full support ≤12.1 |
Safari
Full support 6 |
WebView Android
Full support ≤37 |
Chrome Android
Full support 18 |
Firefox Android
Full support 4 |
Opera Android
Full support ≤12.1 |
Safari iOS
Full support Yes |
Samsung Internet Android
Full support 1.0 |
Legend
- Full support
- Full support
See also
validityState
validityState.valueMissing
validityState.typeMismatch
validityState.patternMismatch
validityState.tooLong
validityState.tooShort
validityState.rangeUnderflow
validityState.rangeOverflow
validityState.stepMismatch
validityState.valid
validityState.customError
HTMLObjectElement.setCustomValidity by Mozilla Contributors is licensed under CC-BY-SA 2.5.