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

如何使用jQuery限制注册邮箱域名与用户输入的网站域名一致

实现方案

1. 核心逻辑说明

  • 首先监听网站输入框的内容变化,提取输入链接的纯域名部分
  • 监听邮箱输入框的输入事件,校验邮箱后缀是否和提取的域名完全匹配
  • 匹配失败时给出提示或者阻断提交即可,不要直接修改用户输入的内容,避免干扰正常输入

2. 域名提取函数实现

可以直接利用浏览器内置的URL对象来解析链接,不需要自己写正则处理各种前缀、路径的情况,兼容性覆盖所有主流浏览器:

function extractDomain(url) {
  // 处理用户没加http/https的情况,自动补全再解析
  if (!/^https?:\/\//i.test(url)) {
    url = 'https://' + url;
  }
  try {
    const urlObj = new URL(url);
    // 返回不带www的纯域名,可根据需求调整是否保留www
    return urlObj.hostname.replace(/^www\./i, '');
  } catch (e) {
    // 输入内容不是合法链接时返回空
    return '';
  }
}

3. 完整表单校验代码

假设你的网站输入框id是website,邮箱输入框id是email,表单id是register-form,代码如下:

<!-- 请提前引入jQuery库 -->
<script>
// 存储提取到的允许使用的域名
let allowedDomain = '';

// 监听网站输入框内容变化
$('#website').on('input change', function() {
  const websiteVal = $(this).val().trim();
  allowedDomain = extractDomain(websiteVal);
  // 网站输入变化后自动触发一次邮箱校验
  $('#email').trigger('input');
});

// 监听邮箱输入实时校验
$('#email').on('input change', function() {
  const emailVal = $(this).val().trim();
  // 未填网站或者未填邮箱时跳过校验
  if (!allowedDomain || !emailVal) {
    $(this).removeClass('invalid');
    $('#email-error').hide();
    return;
  }
  // 校验邮箱后缀是否匹配
  const requiredSuffix = `@${allowedDomain}`;
  const isMatch = emailVal.endsWith(requiredSuffix);
  
  if (isMatch) {
    $(this).removeClass('invalid');
    $('#email-error').hide();
  } else {
    $(this).addClass('invalid');
    $('#email-error').text(`邮箱后缀必须为${requiredSuffix}`).show();
  }
});

// 表单提交前最终校验,避免用户绕过前端校验
$('#register-form').on('submit', function(e) {
  const emailVal = $('#email').val().trim();
  if (allowedDomain && emailVal && !emailVal.endsWith(`@${allowedDomain}`)) {
    e.preventDefault();
    $('#email-error').text(`邮箱后缀必须为@${allowedDomain}`).show();
    return false;
  }
});

// 域名提取函数
function extractDomain(url) {
  if (!/^https?:\/\//i.test(url)) {
    url = 'https://' + url;
  }
  try {
    const urlObj = new URL(url);
    return urlObj.hostname.replace(/^www\./i, '');
  } catch (e) {
    return '';
  }
}
</script>

<!-- 可搭配对应的提示元素和样式 -->
<style>
.invalid { border: 1px solid #f5222d; }
#email-error { color: #f5222d; font-size: 12px; margin-top: 4px; display: none; }
</style>

4. 原有代码问题说明

你之前的代码问题主要有两点:

  • 写死了固定后缀@outlook.com,没有动态读取网站输入的域名
  • indexOf判断逻辑错误,indexOf返回的是匹配字符串的起始下标,不等于1的判断完全不符合需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 08:24:01