ValidityState: customError 属性
ValidityState 接口的只读 customError 属性会在元素不符合通过元素 setCustomValidity() 方法设置的自定义有效性要求时返回 true。
值
如果已将自定义错误消息设置为非空字符串,则返回 true。
示例
检测自定义错误
在此示例中,当表单提交包含被视为无效的用户输入时,setCustomValidity() 会设置自定义错误消息。“验证输入”按钮调用 reportValidity(),当用户输入的值不符合 表单的约束 时,它会在元素下方显示验证消息。
如果您输入文本“good”或“fine”并尝试验证输入,则在清除自定义错误消息(设置为空字符串)之前,该字段将被标记为无效。作为比较,输入元素上有一个 minlength 属性,允许我们在用户输入的字符少于两个时演示 tooShort 有效性状态。当表单控件中的值无效时,即使没有自定义错误,输入也会有一个红色的轮廓。
HTML
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
css
input:invalid {
border: red solid 3px;
}
JavaScript
js
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);
结果
规范
| 规范 |
|---|
| HTML # dom-validitystate-customerror-dev |
浏览器兼容性
加载中…