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

表单空提交时显示自定义提示并阻止提交及邮箱格式校验问题

表单校验失败:页面刷新且未显示提示的解决方法

你的代码存在几个关键问题,导致校验失效且页面刷新:

问题分析

  • 事件绑定位置错误:onsubmit事件应该绑定在<form>标签上,提交按钮本身没有onsubmit属性,当前绑定方式完全无效。
  • 运算符误用:所有if判断里用了赋值符号=,而非比较符号===,这会把空字符串强制赋值给输入框,同时条件永远为真,逻辑完全混乱。
  • 未阻止默认提交行为:即使校验不通过,表单仍会执行默认提交动作,导致页面刷新,错误提示来不及显示。
  • 缺少邮箱格式校验:未实现邮箱格式正确性的验证逻辑。
  • 错误提示未重置:再次提交时,上一次的错误提示不会被清除,影响用户体验。

修正后的完整代码

HTML部分

<form action="" onsubmit="return formValidator(event)">
  <label for="first-name">First name:</label>
  <input type="text" id="first-name">
  <p id="first-p" class="error"></p>
  <br>
  <label for="last-name">Last name:</label>
  <input type="text" id="last-name">
  <p id="last-p" class="error"></p>
  <br>
  <label for="email">Email:</label>
  <input type="email" name="" id="email">
  <p id="email-p" class="error"></p>
  <br>
  <label for="password">Password:</label>
  <input type="password" name="" id="password">
  <p id="password-p" class="error"></p>
  <br>
  <input type="submit" value="Submit">
</form>

JavaScript部分

const fname = document.querySelector("#first-name");
const lname = document.querySelector('#last-name');
const email = document.querySelector('#email');
const password = document.querySelector("#password");
const errorElements = document.querySelectorAll('.error');

function formValidator(event) {
  // 重置所有错误提示
  errorElements.forEach(el => el.textContent = '');
  let isValid = true;

  // 校验名
  if (fname.value.trim() === '') {
    document.getElementById('first-p').textContent = "First name cannot be empty";
    isValid = false;
  }

  // 校验姓
  if (lname.value.trim() === '') {
    document.getElementById('last-p').textContent = 'Last name cannot be empty';
    isValid = false;
  }

  // 校验邮箱
  if (email.value.trim() === '') {
    document.getElementById('email-p').textContent = 'Email cannot be empty';
    isValid = false;
  } else {
    // 邮箱格式校验正则
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(email.value.trim())) {
      document.getElementById('email-p').textContent = 'Please enter a valid email address';
      isValid = false;
    }
  }

  // 校验密码
  if (password.value.trim() === '') {
    document.getElementById('password-p').textContent = 'Password cannot be empty';
    isValid = false;
  }

  // 校验不通过则阻止表单提交
  if (!isValid) {
    event.preventDefault();
  }
  return isValid;
}

关键修改说明

  1. 将onsubmit事件移到<form>标签上,并通过return formValidator(event)传递事件对象,用于阻止默认行为。
  2. 把所有赋值运算符=替换为全等比较运算符===,并增加trim()处理输入前后空格。
  3. 增加event.preventDefault()阻止表单默认提交,只有当所有校验通过时才允许提交。
  4. 添加邮箱格式正则校验,当邮箱非空但格式错误时显示对应提示。
  5. 每次校验前重置所有错误提示,避免旧提示残留。
  6. 使用const声明变量,符合现代JS规范。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 09:43:20