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

如何在HTML input的pattern正则中排除多个字符串?

解决方案

你之前的正则问题在于只添加了负前瞻断言,但没有匹配完整的邮箱字符串,且断言的作用范围未覆盖整个域名规则。要实现禁止@freesite.com和任意子域名.domain2.org的邮箱,需要将负前瞻与完整的邮箱匹配逻辑结合,同时锚定字符串首尾确保校验范围正确。

最终可用的HTML代码

<input type="email" pattern="^(?!.*@(freesite\.com|.*\.domain2\.org)$).+$">

规则拆解

  • ^ 和 $:强制校验整个邮箱字符串,避免部分匹配导致的漏洞
  • (?!.*@(freesite\.com|.*\.domain2\.org)$):负前瞻断言,若邮箱结尾是@freesite.com,或是任意前缀+.domain2.org(比如sub.domain2.org、any.sub.domain2.org),则直接标记为无效
  • .+:利用type="email"的原生基础校验,快速匹配合法邮箱格式(若需要更严格的自定义邮箱格式,可替换为标准邮箱正则)

效果验证

  • 被标记无效的邮箱:
    • user@freesite.com
    • user@subdomain.domain2.org
    • admin@deep.sub.domain2.org
  • 正常通过的邮箱:
    • user@other-domain.com
    • user@domain2.com
    • user@freesite.org

进阶:自定义严格邮箱格式

如果需要同时强化邮箱格式校验,可将.+替换为标准邮箱正则,最终代码如下:

<input type="email" pattern="^(?!.*@(freesite\.com|.*\.domain2\.org)$)[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$">

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 08:50:25