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

如何通过HTML5 Pattern验证邮箱地址不以下划线开头

Fixing HTML5 Email Validation: Preventing Underscore as the First Character

Hey there! Let's get your email validation sorted out. The issue with your initial regex [?!_] is that it's not doing what you think it is—let's break this down step by step.

Why Your Original Regex Failed

[?!_] is a character set, which means it matches any single character that's either ?, !, or _. That's the opposite of what you want (you're trying to exclude underscores at the start), and it doesn't act as a "negative check" for the first character. To enforce that the email doesn't start with an underscore, you need a negative lookahead assertion, not a character set.

The Correct Regex

To validate emails that don't start with an underscore, use this pattern:

^(?!_)[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$

Let's break down what each part does:

  • ^: Anchors the match to the start of the string
  • (?!_): Negative lookahead—this checks that the first character is not an underscore before proceeding
  • [a-zA-Z0-9_.-]+: Matches the local part of the email (before @), allowing letters, numbers, underscores, dots, and hyphens (at least one character)
  • @: Matches the mandatory @ symbol
  • [a-zA-Z0-9-]+: Matches the domain name (e.g., gmail, company)
  • \.[a-zA-Z0-9-.]+$: Matches the domain suffix (e.g., .com, .co.uk) and anchors to the end of the string

Implementing in HTML5

Here's how to use this regex with the pattern attribute in an email input. We'll also add a title attribute to show a helpful error message when validation fails:

<label for="user-email">Your Email:</label>
<input 
  type="email" 
  id="user-email" 
  name="user-email"
  pattern="^(?!_)[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$"
  title="Email cannot start with an underscore. Please enter a valid email address."
  required
>

Notes for Edge Cases

  • If you need to support more complex email formats (like quotes or special characters allowed in RFC 5322), you can expand the local part character set—but the core (?!_) assertion will still work to block leading underscores.
  • The type="email" attribute already provides basic validation, but combining it with pattern adds your custom rule against leading underscores.

内容的提问来源于stack exchange,提问作者Mohammad Faizan Zafar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 09:04:34