我表单通常验证的方法:
首先提交按钮先是disabled = true,表单元素变化时才进行验证,并且是一项一项的验证,这样用户体验会比较好,尤其是表单特别长的时候。具体实现的方法就是当前项目选择验证主要用到onChange(或者keyUp)和onBlur,和form.checkValidity(),如下面例子:
<form id="form">
<div>
<label for="name">姓名</label>
<input type="text" id="name" name="name" required />
<span id="tip" style="display: none">请输入姓名</span>
</div>
<div>
<label for="sex">性别</label>
<input type="text" id="sex" name="sex" />
</div>
</form>
<button id="submit" disabled>提交</button>
<script>
let form = document.getElementById('form')
let name = document.getElementById('name')
let submit = document.getElementById('submit')
let tip = document.getElementById('tip')
function checkValid(e) {
if(e.target.reportValidity()) {
(form.checkValidity()) && (submit.disabled = false);
tip.style.display = 'none'
} else {
submit.disabled = true
tip.style.display = 'inline'
}
}
name.addEventListener('change', checkValid, false)
name.addEventListener('blur', checkValid, false)
</script>
效果: