输入框无效状态背景色设置:卡号验证失败样式与提交异常问题
问题根因
- 卡号输入框仅用了默认的
required校验规则,浏览器无法识别Luhn校验结果,只要输入不为空就会被判定为valid状态,因此始终显示绿色背景 - 表单提交逻辑没有关联Luhn校验规则,只要原生表单校验(必填、格式匹配)通过就会触发提交,不会拦截Luhn校验失败的情况
修复步骤
1. 修正卡号输入框的事件逻辑
删除冗余引号,添加HTML5自定义校验逻辑,校验失败时调用setCustomValidity标记输入框为无效状态,校验通过时清空自定义错误标记,同时把原本的全局存储变量优化为元素自定义属性,避免全局污染:
<input id="cardInput" type="text" size="24" maxlength="20" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');" name="cc_number" onblur=" // 存储输入值,剥离非数字字符 this.dataset.ccSaved = this.value; this.value = this.value.replace(/[^\d]/g, ''); if(!checkLuhn(this.value)) { alert('Sorry, that is not a valid number - please try again!'); // 标记为校验不通过,匹配CSS错误样式 this.setCustomValidity('Invalid card number'); } else { // 校验通过清空错误标记 this.setCustomValidity(''); }" onfocus=" // 恢复存储的输入值 if(this.value != this.dataset.ccSaved) this.value = this.dataset.ccSaved; " placeholder="Enter a Proxy Credit Card Number." required />
2. 添加表单提交拦截逻辑
在原有JS代码的checkLuhn函数后新增表单提交监听,提交前二次校验卡号,不通过则阻止提交:
document.getElementById('form').addEventListener('submit', function(e) { const cardInput = document.getElementById('cardInput'); const pureCardValue = cardInput.value.replace(/[^\d]/g, ''); if(!checkLuhn(pureCardValue)) { e.preventDefault(); alert('Sorry, that is not a valid number - please try again!'); cardInput.setCustomValidity('Invalid card number'); return false; } cardInput.setCustomValidity(''); });
原有CSS代码无需修改,可直接适配自定义校验的valid/invalid状态。
内容的提问来源于stack exchange,提问作者jammydodger
相关产品推荐
相关产品推荐

