HTML表单年龄与出生年份验证失效问题求助
修复年龄与出生年份匹配验证的问题
你已经精准定位到了代码里的两处问题,下面是修复后的完整代码,以及具体的改动说明:
问题分析
- 问题1:元素获取错误:获取出生年份输入框值时,
getElementById('yearborn')前面缺少document前缀,浏览器会识别为未定义的函数,导致无法正确获取输入值。 - 问题2:类型不匹配导致比较失效:输入框返回的是字符串类型,直接用
n - age !== yearBorn做数值比较时,字符串和数字的不严格相等判断会出错,必须先把获取到的值转为数字类型。
修复后的完整代码
JavaScript部分
function formError() { // 验证姓名输入 if (document.getElementById('name').value == "") { alert('Please enter your name.'); document.getElementById('name').style.borderColor = "red"; return false; } // 验证出生年份输入 const yearBornInput = document.getElementById('yearborn'); if (yearBornInput.value == "") { alert('Please enter the year you were born.'); yearBornInput.style.borderColor = "red"; return false; } // 验证年龄输入 const ageInput = document.getElementById('age'); if (ageInput.value == "") { alert('Please enter your age.'); ageInput.style.borderColor = "red"; return false; } // 获取当前年份 const currentYear = new Date().getFullYear(); // 转换为数字类型 const age = Number(ageInput.value); const yearBorn = Number(yearBornInput.value); // 验证年龄与出生年份是否匹配 if (currentYear - age !== yearBorn) { alert('Please make sure that your age and year born is correct.'); return false; } // 所有验证通过时返回true(可选,若需要表单提交则保留) return true; }
HTML部分
<fieldset> <form id="frmName" method="post" action="#" onsubmit="return formError()"> <h1>Inf115 compulsory assignment 3</h1> <p> <b>Name:</b><input type="text" id="name" name="name" maxlength="20" /> </p> <p> <b>Year of birth:</b><input type="number" id="yearborn" maxlength="4" /> </p> <p> <b>Age:</b><input type="number" id="age" maxlength="3" /> </p> <p> <input type="submit" value="Submit" /> <input type="reset" value="Reset" /> </p> </form> </fieldset>
额外优化说明
- 把获取元素的操作提前并赋值给变量,避免重复调用
document.getElementById,提升代码效率; - 把HTML里的
type=int改成标准的type="number",这样浏览器会自动限制输入为数字,减少非数字输入的情况; - 添加了验证通过时的
return true,确保表单在验证通过后能正常提交(如果需要的话)。
内容的提问来源于stack exchange,提问作者ifailatmathz
相关产品推荐
相关产品推荐

