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

如何在HTML中添加仅允许@gmail.com和@yahoo.com的特定邮箱验证规则

实现方案

方案1:仅用HTML原生属性实现

直接利用input标签的pattern自定义正则校验规则即可,无需额外写JS代码,示例如下:

<form action="" method="post">
  <label for="email">邮箱地址:</label>
  <input 
    type="email" 
    id="email" 
    name="email"
    pattern="^[a-zA-Z0-9_.+-]+@(gmail|yahoo)\.com$"
    title="仅允许@gmail.com或@yahoo.com后缀的邮箱地址"
    required
  >
  <button type="submit">提交</button>
</form>

各属性作用说明:

  • type="email" 保留原生邮箱格式基础校验,先过滤不符合基本邮箱格式的内容
  • pattern 自定义正则规则,精准限制后缀只能是@gmail.com或@yahoo.com
  • title 在校验不通过时,会作为原生弹窗的补充提示内容展示给用户
  • required 限制该字段为必填项

方案2:配合JavaScript做更灵活的校验

如果需要自定义提示样式、实时校验等效果,可以搭配JS实现,示例如下:

<form action="" method="post" id="emailForm">
  <label for="email">邮箱地址:</label>
  <input type="email" id="email" name="email" required>
  <span id="emailError" style="color: red; display: none;">仅允许@gmail.com或@yahoo.com后缀的邮箱地址</span>
  <button type="submit">提交</button>
</form>

<script>
const form = document.getElementById('emailForm');
const emailInput = document.getElementById('email');
const errorTip = document.getElementById('emailError');

form.addEventListener('submit', function(e) {
  const emailValue = emailInput.value.trim();
  const allowedSuffix = ['@gmail.com', '@yahoo.com'];
  // 检查邮箱后缀是否在允许列表内
  const isValid = allowedSuffix.some(suffix => emailValue.endsWith(suffix));
  
  if (!isValid) {
    e.preventDefault();
    errorTip.style.display = 'inline';
  } else {
    errorTip.style.display = 'none';
  }
})
</script>

这种方案的优势是后续要新增允许的邮箱后缀时,直接往allowedSuffix数组里加内容即可,不需要修改正则规则,维护成本更低。

重要提醒

所有前端校验都仅做用户体验优化使用,必须在后端服务增加相同的校验规则,避免恶意用户绕过前端校验提交不符合要求的内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 12:54:09