HTML validity对象
validity对象是表单元素的只读属性,提供详细的验证状态信息,每个布尔属性对应一种验证失败类型。
基本语法
JavaScript
const input = document.querySelector('input');
console.log(input.validity); // ValidityState对象
console.log(input.validity.valid); // 整体验证是否通过
属性列表
| 属性 | 说明 | 触发条件 |
|---|---|---|
| valid | 整体验证状态 | 所有验证通过时为true |
| valueMissing | 值缺失 | required字段为空 |
| typeMismatch | 类型不匹配 | email/url格式错误 |
| patternMismatch | 正则不匹配 | pattern验证失败 |
| tooLong | 超出最大长度 | 超过maxlength |
| tooShort | 小于最小长度 | 小于minlength |
| rangeUnderflow | 小于最小值 | 小于min |
| rangeOverflow | 大于最大值 | 大于max |
| stepMismatch | 步进不匹配 | 不符合step要求 |
| badInput | 无效输入 | 浏览器无法转换的值 |
| customError | 自定义错误 | 调用setCustomValidity()后 |
代码示例
检测具体错误类型
HTML
<form id="userForm">
<label>用户名(必填,6-12位):</label>
<input type="text" name="username"
required minlength="6" maxlength="12"
id="usernameInput">
<span id="usernameError"></span>
<br><br>
<label>邮箱:</label>
<input type="email" name="email" id="emailInput">
<span id="emailError"></span>
<br><br>
<label>年龄(18-100):</label>
<input type="number" name="age" min="18" max="100" id="ageInput">
<span id="ageError"></span>
<br><br>
<button type="submit">提交</button>
</form>
<script>
const form = document.getElementById('userForm');
form.addEventListener('submit', (e) => {
const username = document.getElementById('usernameInput');
const email = document.getElementById('emailInput');
const age = document.getElementById('ageInput');
// 检查用户名
if (username.validity.valueMissing) {
document.getElementById('usernameError').textContent = '用户名不能为空';
e.preventDefault();
} else if (username.validity.tooShort) {
document.getElementById('usernameError').textContent = '用户名至少6个字符';
e.preventDefault();
} else if (username.validity.tooLong) {
document.getElementById('usernameError').textContent = '用户名最多12个字符';
e.preventDefault();
}
// 检查邮箱
if (email.validity.typeMismatch) {
document.getElementById('emailError').textContent = '请输入有效的邮箱地址';
e.preventDefault();
}
// 检查年龄
if (age.validity.rangeUnderflow) {
document.getElementById('ageError').textContent = '年龄不能小于18岁';
e.preventDefault();
} else if (age.validity.rangeOverflow) {
document.getElementById('ageError').textContent = '年龄不能大于100岁';
e.preventDefault();
}
});
</script>
实时验证反馈
HTML
<form>
<label>密码(8-16位):</label>
<input type="password" id="pwdInput"
minlength="8" maxlength="16"
required>
<span id="pwdMsg"></span>
</form>
<script>
const pwdInput = document.getElementById('pwdInput');
const pwdMsg = document.getElementById('pwdMsg');
pwdInput.addEventListener('input', () => {
const v = pwdInput.validity;
if (v.valueMissing) {
pwdMsg.textContent = '密码不能为空';
pwdMsg.style.color = 'red';
} else if (v.tooShort) {
pwdMsg.textContent = `还差${8 - pwdInput.value.length}个字符`;
pwdMsg.style.color = 'orange';
} else if (v.valid) {
pwdMsg.textContent = '密码格式正确';
pwdMsg.style.color = 'green';
}
});
</script>
综合验证函数
JavaScript
function validateInput(input) {
const v = input.validity;
const errors = [];
if (v.valueMissing) errors.push('此项必填');
if (v.typeMismatch) errors.push('格式不正确');
if (v.patternMismatch) errors.push('不符合要求的格式');
if (v.tooShort) errors.push(`至少需要${input.minLength}个字符`);
if (v.tooLong) errors.push(`最多允许${input.maxLength}个字符`);
if (v.rangeUnderflow) errors.push(`不能小于${input.min}`);
if (v.rangeOverflow) errors.push(`不能大于${input.max}`);
if (v.stepMismatch) errors.push('请按正确步进输入');
return {
isValid: v.valid,
errors: errors
};
}
// 使用示例
const input = document.querySelector('input');
const result = validateInput(input);
if (!result.isValid) {
console.log(result.errors.join(','));
}
注意:validity对象的属性是只读的,只能通过修改输入值或调用setCustomValidity()来改变验证状态。
要点总结
- validity对象包含10个布尔属性,精确描述验证失败原因
- validity.valid为true表示所有验证通过
- 只能读取,不能直接修改属性值
- 常用于自定义错误提示信息的显示逻辑
- 配合input事件可实现实时验证反馈
📝 发现内容有误?点击此处直接编辑