全部学科
Python全栈
python
NodeJS全栈
nodejs
小程序首页
📅 2026-05-17 6 分钟 ✍️ juanwangdev

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()来改变验证状态。

要点总结

  1. validity对象包含10个布尔属性,精确描述验证失败原因
  2. validity.valid为true表示所有验证通过
  3. 只能读取,不能直接修改属性值
  4. 常用于自定义错误提示信息的显示逻辑
  5. 配合input事件可实现实时验证反馈

📝 发现内容有误?点击此处直接编辑

← 上一篇 HTML type属性验证类型
下一篇 → HTML原生表单验证
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库