You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript表单控件校验失效 空输入仍提交跳转问题解决

表单提交校验失效修复

问题表现

给表单输入项添加JavaScript校验规则,要求仅当输入内容符合预设要求时,才允许提交表单并跳转到目标地址。代码运行时控制台没有报错,但即使用户完全不填写任何输入项,点击提交按钮后表单依然会提交并跳转到下一页。

原始问题代码

校验逻辑JS代码

// 表单控件获取
const form = document.getElementById('form');
const username = document.getElementById('username');
const room = document.getElementById('room');

// 展示输入错误提示
function showError(input, message) {
  const formControl = input.parentElement;
  formControl.className = 'form-control error';
  const small = formControl.querySelector('small');
  small.innerText = message;
}

// 展示校验通过样式
function showSuccess(input) {
  const formControl = input.parentElement;
  formControl.className = 'form-control success';
}


// 必填项校验
function checkRequired(inputArr) {
  inputArr.forEach(function(input) {
    if (input.value.trim() === '') {
      showError(input, `${getFieldName(input)}不能为空`);
    } else {
      showSuccess(input);
    }
  });
}

// 获取字段中文名称
function getFieldName(input) {
  const fieldMap = {
    username: '用户名',
    room: '房间号'
  }
  return fieldMap[input.id] || input.id;
}

// 事件监听
form.addEventListener('submit', function(e) {
  e.preventDefault();
  checkRequired([username]);
});

页面结构HTML代码

<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="../static/style.css" rel="stylesheet">
  <title>聊天室</title>
  <script src="{{ url_for('static', filename='scripts.js') }}"></script>
</head>

<body>
  <div class="container-head">
    <div class="header">
      <h1>MyApp</h1>
    </div>
  </div>

  <div class="container">
    <form action="{{url_for('chat') }}" class="form" id="form" method="POST">

      <div class="form-control">
        <input type="text" id="username" name="username" placeholder="请输入用户名">
        <small>错误提示</small>
      </div>
      <div class="form-control">
        <input type="text" id="room" name="room" placeholder="请输入房间号">
        <small>错误提示</small>
      </div>

      <button type="submit" class="btn btn-big">开始聊天</button>
    </form>

  </div>

</body>

</html>

问题原因

  • 校验函数没有返回结果:原始的checkRequired函数只做了样式切换和提示渲染,没有返回布尔值标识整体校验是否通过,代码无法判断是否满足提交条件
  • 校验字段遗漏:提交逻辑里只把username传入了校验函数,漏掉了同样是必填项的room字段
  • 缺少校验结果判断:阻止表单默认提交行为后,没有根据校验结果判断是否需要执行提交操作,逻辑不闭环

修复后可运行代码

修复点包括:给校验函数增加结果返回逻辑、新增输入长度校验规则、补全校验字段范围,仅当所有校验项全部通过时才触发表单提交,校验不通过时仅展示对应错误提示,不会执行跳转:

// 必填项校验
function checkRequired(inputArr) {
  let isPass = true;
  inputArr.forEach(function(input) {
    if (input.value.trim() === '') {
      isPass = false;
      showError(input, `${getFieldName(input)}不能为空`);
    } else {
      showSuccess(input);
    }
  });
  return isPass;
}  

// 输入长度校验
function checkLength(input, min, max) {
  let isPass = true;
  if(input.value.length < min) {
    showError(input, `${getFieldName(input)}长度不能少于${min}个字符`);
    isPass = false;
  } else if(input.value.length > max) {
    showError(input, `${getFieldName(input)}长度不能超过${max}个字符`);
    isPass = false;
  } else {
    showSuccess(input);
  }
  return isPass;
}

// 获取字段中文名称
function getFieldName(input) {
  const fieldMap = {
    username: '用户名',
    room: '房间号'
  }
  return fieldMap[input.id] || input.id;
}
  
// 提交事件监听
form.addEventListener('submit', function(e) {
  e.preventDefault();
  // 所有校验通过才提交表单
  if(checkRequired([username, room]) && checkLength(username, 3, 15)){
    form.submit();
  }      
});   

内容的提问来源于stack exchange,提问作者robothead

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 04:54:28