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

护照号码正则表达式验证实现问题求助

Fixing Passport Number Validation Regex

Hey there! Let's get your passport number regex working correctly based on the rules you outlined. First, let's recap what we need to enforce:

Requirements Recap

  • Length must be between 5-20 characters
  • Only alphanumeric characters allowed (a-z, A-Z, 0-9), case-insensitive
  • Cannot consist entirely of a single repeated character (e.g., all 1s or all As are invalid)

What's Wrong With Your Current Regex?

Your regex /^(.){2,}[A-Za-z0-9]{5,20}$/ doesn't address the core requirements properly:

  • It miscalculates valid lengths (the {2,} plus {5,20} allows 7-22 characters, which breaks your 5-20 rule)
  • It has no logic to block strings made of a single repeated character
  • The opening (.){2,} allows any character (not just alphanumeric) at the start, violating your allowed characters constraint

The Correct Regex

Here's a regex that checks all your boxes:

/^(?!(.)\1+$)[A-Za-z0-9]{5,20}$/i

Breakdown of the Regex

Let's walk through each part to understand how it enforces your rules:

  • ^: Anchors the match to the start of the string
  • (?!(.)\1+$): Negative lookahead that blocks invalid single-character repeated strings:
    • (.): Captures any single character
    • \1+: Matches one or more instances of the captured character
    • $: Ensures this repetition goes all the way to the end of the string
  • [A-Za-z0-9]{5,20}: Matches exactly 5 to 20 alphanumeric characters
  • $: Anchors the match to the end of the string
  • /i: Case-insensitive modifier, so we don't have to distinguish between uppercase and lowercase letters (perfect for passport numbers, which are usually case-agnostic)

Testing Against Your Examples

Let's verify this regex with your test cases:

  • 11111111: ❌ Fails (all characters are identical, blocked by the negative lookahead)
  • 111112: ✅ Passes (valid length, mixed characters, all alphanumeric)
  • fdgADGF12: ✅ Passes (valid length, mixed alphanumerics, no single repeated character)
  • AAAAAAAAAAA: ❌ Fails (all characters are identical)
  • bbbbbbb: ❌ Fails (all characters are identical)

If you ever need case-sensitive validation (though it's rare for passport numbers), just remove the /i modifier at the end.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 15:24:08