基于JavaScript的大小写兼容文本密码验证方案及代码正确性咨询
文本密码验证功能的代码规范与优化建议
问题背景
需要实现支持大小写输入的文本密码验证功能:输入「human」或「human being」时跳转至页面A,输入其他文本跳转至页面B,现有代码如下,需评估规范度并优化。
现有代码
HTML部分
<form> <div class="puzzle"> <label for="password"> <i>Which animal has four legs in the morning, two in the afternoon, and three legs at night?</i> </label> <input type="text" id="password" autocomplete="off" placeholder="Your answer" required="required"> </div> <input type="button" class="btn" onclick="checkPassword()" value="Answer"> </form>
JavaScript部分
function checkPassword() { var password = $('#password').val(); if (password == 'human being') { window.location.href = '../minotaur/' } else { window.location.href = '../sphinxDead/'; } }
现有代码的问题
- 依赖未明确:代码使用了jQuery选择器
$('#password'),但未说明页面是否引入jQuery库,缺失的话会直接报错。 - 不支持大小写输入:当前判断是严格大小写匹配,用户输入「Human」「HUMAN BEING」会被判定错误,不符合需求。
- 表单校验失效:按钮为
type="button",不会触发表单默认的required校验逻辑,空输入也会执行跳转。 - 未覆盖全部正确答案:只判断了「human being」,遗漏了需求中的「human」。
- 内联事件不规范:直接在HTML中写
onclick,不利于代码维护和事件管理。
优化后的代码方案
方案1:原生JavaScript版本(无框架依赖)
<form id="answerForm"> <div class="puzzle"> <label for="password"> <i>Which animal has four legs in the morning, two in the afternoon, and three legs at night?</i> </label> <input type="text" id="password" autocomplete="off" placeholder="Your answer" required > </div> <button type="submit" class="btn">Answer</button> </form>
// 确保DOM加载完成后绑定事件,避免元素未找到的报错 document.addEventListener('DOMContentLoaded', function() { const answerForm = document.getElementById('answerForm'); const answerInput = document.getElementById('password'); answerForm.addEventListener('submit', function(e) { e.preventDefault(); // 阻止表单默认提交行为 // 去除首尾空格并转小写,实现大小写不敏感+兼容误输入空格 const userAnswer = answerInput.value.trim().toLowerCase(); // 用数组存储正确答案,后续新增只需修改数组 const correctAnswers = ['human', 'human being']; if (correctAnswers.includes(userAnswer)) { window.location.href = '../minotaur/'; } else { window.location.href = '../sphinxDead/'; } }); });
方案2:jQuery版本(若需保留jQuery)
<form id="answerForm"> <div class="puzzle"> <label for="password"> <i>Which animal has four legs in the morning, two in the afternoon, and three legs at night?</i> </label> <input type="text" id="password" autocomplete="off" placeholder="Your answer" required > </div> <button type="submit" class="btn">Answer</button> </form>
$(document).ready(function() { $('#answerForm').on('submit', function(e) { e.preventDefault(); const userAnswer = $('#password').val().trim().toLowerCase(); const correctAnswers = ['human', 'human being']; if (correctAnswers.includes(userAnswer)) { window.location.href = '../minotaur/'; } else { window.location.href = '../sphinxDead/'; } }); });
优化说明
- 改用表单
submit事件,配合required属性自动校验非空输入,无需手动判断。 - 对输入值做「去首尾空格+转小写」处理,完美支持大小写输入,同时兼容用户误输入的空格。
- 用数组存储正确答案,后续扩展只需修改数组,维护成本更低。
- 采用DOM加载完成后绑定事件的方式,避免元素未加载导致的报错。
- 移除内联
onclick,符合现代前端代码的可维护性要求。
内容的提问来源于stack exchange,提问作者Giovana
相关产品推荐
相关产品推荐

