HTMLObjectElement:setCustomValidity() 方法
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.
HTMLObjectElement
接口的 setCustomValidity()
方法设置元素的自定义校验消息。
语法
js
setCustomValidity(errorMessage)
参数
errorMessage
-
用于校验错误的消息。
返回值
无 (undefined
)。
异常
无。
示例
在这个示例中,我们传入输入元素的 ID,并根据该值是缺失、过小或过大设置不同的错误消息。此外,你必须对同一元素调用 reportValidity 方法,否则什么事都不会发生。
js
function validate(inputID) {
const input = document.getElementById(inputID);
const validityState = input.validity;
if (validityState.valueMissing) {
input.setCustomValidity("你必须填满这个,哟!");
} else if (validityState.rangeUnderflow) {
input.setCustomValidity("我们需要一个更大的数字!");
} else if (validityState.rangeOverflow) {
input.setCustomValidity("太大了!");
} else {
input.setCustomValidity("");
}
input.reportValidity();
}
如果没有错误,将消息设置为空字符串是至关重要的。只要错误消息不为空,表单就不会验证通过,也不会被提交。
规范
Specification |
---|
HTML # dom-cva-setcustomvalidity-dev |
浏览器兼容性
Report problems with this compatibility data on GitHubdesktop | mobile | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
setCustomValidity |
Legend
Tip: you can click/tap on a cell for more information.
- Full support
- Full support
- See implementation notes.
The compatibility table on 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.