You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何type为email的空输入框调用checkValidity()会返回true?

问题原因与解决方法

为什么空值时checkValidity()返回true?

HTML5的email类型输入框默认验证逻辑是:只有输入框有内容时,才会校验格式是否符合邮箱规范。空值属于「未填写」状态,不会触发验证失败,因此checkValidity()会返回true。

解决方法

要让空值也触发验证失败,给输入框添加required属性即可,强制要求用户必须填写内容。

修改后的代码如下:

HTML部分

<input placeholder="Email Address" class="user-input__form-email" required>

JS部分

let email = document.getElementsByClassName("user-input__form-email")[0];

email.type = "email";
console.log("email " + email.value + "  " + email.checkValidity());

if (email.checkValidity() === false) {
  emailError.style.display = "block";
}

添加required后,输入框为空时checkValidity()会返回false,符合预期的验证逻辑。

内容的提问来源于stack exchange,提问作者vikramvi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 02:10:37