概述HTML 提供内建约束校验(`required/min/max/pattern/type` 等),并通过 Constraint Validation API 暴露状态与方法。可在不依赖第三方库的情况下实现一致的校验与提示。示例<form id="f">
<input id="email" type="email" required>
<button>提交</button>
</form>
<script>
const el = document.getElementById('email')
el.addEventListener('input', () => {
if (!el.validity.valid) {
el.setCustomValidity('请输入有效邮箱')
} else {
el.setCustomValidity('')
}
})
document.getElementById('f').addEventListener('submit', e => {
if (!el.reportValidity()) e.preventDefault()
})
</script>
工程建议文本与国际化:使用本地化提示文案;避免仅用颜色表示错误(无障碍)。交互:在失焦或提交时提示;高优先级错误优先展示。安全:前端校验只是体验;后端需重复校验并防注入。参考与验证MDN Constraint Validation 文档:https://developer.mozilla.org/docs/Web/Guide/HTML/Constraint_validationWHATWG HTML 规范(表单约束):https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#constraint-validation

发表评论 取消回复