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

邮箱验证失效及表单提交后数据跳转展示问题求助

问题1:邮箱输入内容后验证失效的原因及修复
  • 核心原因:正则表达式使用了/gm全局匹配标志,RegExp.test()方法在全局模式下会维护一个lastIndex属性,记录下一次匹配的起始位置。第一次调用test()后,lastIndex会被设置为匹配结束的位置,第二次调用时会从这个位置开始匹配,导致原本有效的邮箱也返回false。
  • 修复方案:移除正则的/gm标志(邮箱验证不需要全局或多行匹配),同时补充错误状态重置逻辑(避免错误样式残留):
let emailInput = document.querySelector(".email"),
  form = document.querySelector(".form");
  
form.addEventListener("submit", (e) => {
  e.preventDefault();
  // 重置错误状态
  emailInput.classList.remove("error-border");
  document.querySelector(".valid-notice").style.display = "none";

  if (!test(emailInput.value.trim())) { // 增加trim()处理首尾空格
    errorEmail(emailInput);
  } else {
    e.currentTarget.submit();
  }
});

function test(email) {
  // 移除/gm标志
  let validEmail = /^[^\.\s][\w\-]+(\.[\w\-]+)*@([\w-]+\.)+[\w-]{2,}$/;
  return validEmail.test(email);
}

function errorEmail(input) {
  let valid = document.querySelector(".valid-notice");
  input.classList.add("error-border");
  valid.style.display = "inline-block";
}
问题2:提交表单后打开新页面并显示输入数据

步骤1:修改原表单的target属性

将表单的target="_self"改为target="_blank",确保提交后在新窗口打开目标页面:

<form method="get" class="form" action="./subscript.html" target="_blank">
  <small>Email address</small>
  <small class="valid-notice">Valid email required</small>

  <input class="email" type="email" name="email" placeholder="email@company.com"/>
  <input class="submit-btn" type="submit" value="Subscribe to monthly newsletter"/>
</form>

步骤2:创建subscript.html页面并获取URL参数

在subscript.html中,通过URL查询参数提取邮箱地址并展示:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <title>订阅确认</title>
</head>
<body>
  <div id="confirm-message"></div>
  <script>
    // 从URL中获取email参数
    const params = new URLSearchParams(window.location.search);
    const userEmail = params.get('email');
    // 渲染确认信息
    document.getElementById('confirm-message').textContent = `已向${userEmail}发送确认邮件`;
  </script>
</body>
</html>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 19:48:31