JavaScript表单验证问题:添加地址与电话字段后验证失效求助
解决表单添加地址、电话字段后验证失效的问题
看起来你是在给原有表单新增地址和电话号码字段后,验证逻辑没补全导致功能失效了。我帮你把代码修正完整,同时保留原有的验证逻辑,还新增了电话号码的格式校验,你可以直接用:
完整可运行代码
<form action="" name="form1"> Please enter the following details: <p> Name: <input type="text" name="txtName" /> </p> <p> Age: <input type="text" name="txtAge" size="3" maxlength="3" /> </p> <p> Address: <input type="text" name="txtAddress" /> </p> <p> Telephone: <input type="text" name="txtTelNumber" /> </p> <p> <input type="button" value="Check details" name="btnCheckForm"> </p> </form> <script> var myForm = document.form1; function btnCheckFormClick(e) { var txtName = myForm.txtName; var txtAge = myForm.txtAge; var txtAddress = myForm.txtAddress; var txtTelNumber = myForm.txtTelNumber; // 检查所有必填字段是否为空 if (txtName.value === "" || txtAge.value === "" || txtAddress.value === "" || txtTelNumber.value === "") { alert("Please complete all of the form"); // 按顺序定位到第一个为空的字段 if (txtName.value === "") { txtName.focus(); } else if (txtAge.value === "") { txtAge.focus(); } else if (txtAddress.value === "") { txtAddress.focus(); } else { txtTelNumber.focus(); } } else { alert("Thanks for completing the form " + txtName.value); } } function txtAgeBlur(e) { var target = e.target; if (isNaN(target.value) || target.value === "") { alert("Please enter a valid age"); target.focus(); target.select(); } } // 新增电话号码格式验证 function txtTelNumberBlur(e) { var target = e.target; // 简单验证:只能是数字,你可以根据需求修改规则(比如允许横杠、加号等) if (isNaN(target.value) || target.value === "") { alert("Please enter a valid telephone number"); target.focus(); target.select(); } } function txtNameChange(e) { alert("Hi " + e.target.value); } // 绑定所有事件 myForm.txtName.addEventListener("change", txtNameChange); myForm.txtAge.addEventListener("blur", txtAgeBlur); myForm.txtTelNumber.addEventListener("blur", txtTelNumberBlur); myForm.btnCheckForm.addEventListener("click", btnCheckFormClick); </script>
关键修改点说明
- HTML部分:新增了地址和电话号码的输入框,确保
name属性和JS中获取元素的名称完全一致 - 提交验证逻辑:
- 新增获取
txtAddress和txtTelNumber元素 - 更新了空值检查的条件,把新增字段加入必填校验
- 优化了焦点定位逻辑,按顺序找到第一个未填写的字段并聚焦,提升用户体验
- 新增获取
- 新增电话验证:添加了
txtTelNumberBlur函数,验证电话号码是否为有效数字,同时绑定了blur事件,和年龄验证逻辑保持一致 - 完善年龄验证:原代码中如果年龄为空时不会触发提示,现在补充了空值检查,让逻辑更严谨
内容的提问来源于stack exchange,提问作者Melisa
相关产品推荐
相关产品推荐

