原生JS实现表单校验失败时动态禁用提交按钮的方法
实现方法
在你现有代码基础上做少量修改即可实现按钮状态动态控制,核心逻辑是每次执行字段校验时,同步统计每个字段的校验是否通过,只有三个字段全部符合规则时才移除按钮的禁用状态。
具体修改点:
- 页面初始加载时默认将提交按钮设为禁用,避免未输入任何内容时按钮可点击
- 在校验函数中为每个字段增加布尔类型的校验状态标记,每个字段的校验分支中同步更新对应标记的值
- 所有字段校验完成后,根据三个标记的汇总结果设置按钮的
disabled属性 - 额外补充
change事件监听,覆盖浏览器自动填充、鼠标右键粘贴等不会触发keyup的场景,避免校验不触发
修改后可直接运行的代码:
<script> const form = document.getElementById('signup-form'); const name = document.getElementById('name'); const email = document.getElementById('email'); const password = document.getElementById('password'); const submitBtn = document.getElementById("signup-button"); // 初始状态禁用提交按钮 submitBtn.disabled = true; // 绑定输入事件触发校验 form.addEventListener('keyup', checkValidation); form.addEventListener('change', checkValidation); function checkValidation() { const nameValue = name.value.trim(); const emailValue = email.value.trim(); const passwordValue = password.value.trim(); const emailReg = /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/; // 各字段校验状态 let nameValid = false; let emailValid = false; let passwordValid = false; // 姓名校验逻辑 if (!nameValue) { document.getElementById('name-error').style.display = 'block'; document.getElementById('name-error').innerText = "Name Cannot be blank"; nameValid = false; } else { document.getElementById('name-error').style.display = 'none'; nameValid = true; } // 邮箱校验逻辑 if (!emailValue) { document.getElementById('email-error').style.display = 'block'; document.getElementById('email-error').innerText = "Email Cannot be blank"; emailValid = false; } else if (!emailReg.test(emailValue)) { document.getElementById('email-error').style.display = 'block'; document.getElementById('email-error').innerText = "Please Enter a Valid email"; emailValid = false; } else { document.getElementById('email-error').style.display = 'none'; emailValid = true; } // 密码校验逻辑 if (!passwordValue) { document.getElementById('password-error').style.display = 'block'; document.getElementById('password-error').innerText = "Password Cannot be blank"; passwordValid = false; } else { document.getElementById('password-error').style.display = 'none'; passwordValid = true; } // 所有字段校验通过才启用按钮 submitBtn.disabled = !(nameValid && emailValid && passwordValid); } </script>
后续如果需要新增校验规则(比如密码最少6位、姓名不能包含特殊字符等),只需要修改对应字段的校验分支、更新对应的
xxValid值即可,按钮状态控制逻辑不需要调整。
内容的提问来源于stack exchange,提问作者Tushar Arora
相关产品推荐
相关产品推荐

