HTMLObjectElement.setCustomValidity - Web APIs 编辑
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 Standard The definition of 'setCustomValidity' in that specification. | Living Standard | Initial definition. |
Browser compatibility
BCD tables only load in the browser
See also
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论