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

如何阻止表单未填写内容时点击提交跳转至下一页

解决表单空提交跳转的问题

首先你代码里有个严重问题:HTML不允许嵌套

标签,当前提交按钮放在内层form中会导致表单行为异常,先修复这个结构问题——删掉内层的<form>和</form>标签,把提交按钮直接放在外层表单内。

接下来提供两种实现“仅填写内容后允许提交”的方法:

方法一:HTML原生验证(无需JS,最简单)

给用户名、密码输入框添加required属性,浏览器会自动校验输入是否为空,为空时点击提交会阻止跳转并弹出默认提示。

修复后的完整代码:

<form action="form" method="post" style="text-align:center;margin-top:30px;">
  {% csrf_token %}
  <input type="text" name="username" placeholder="enter your user name " required><br>
  <input type="password" name="password" placeholder="enter your password " required><br>

  <button type="submit" class="button">Submit</button>
</form>
<form method="get" action="register" style="text-align:center;margin-top:30px;">
  <button type="submit">Register</button>
</form>

方法二:JavaScript自定义验证(更灵活)

如果需要自定义提示内容或更复杂的校验逻辑,可以用JS监听表单提交事件,手动判断输入是否为空:

<form id="loginForm" action="form" method="post" style="text-align:center;margin-top:30px;">
  {% csrf_token %}
  <input type="text" name="username" placeholder="enter your user name "><br>
  <input type="password" name="password" placeholder="enter your password "><br>

  <button type="submit" class="button">Submit</button>
</form>
<form method="get" action="register" style="text-align:center;margin-top:30px;">
  <button type="submit">Register</button>
</form>

<script>
document.getElementById('loginForm').addEventListener('submit', function(e) {
  const username = this.username.value.trim();
  const password = this.password.value.trim();
  
  if (!username || !password) {
    e.preventDefault(); // 阻止表单默认提交跳转
    alert('请填写用户名和密码!'); // 自定义提示
  }
});
</script>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 23:22:39