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

JavaScript正则表达式验证姓氏:禁止全大写或全小写格式

Surname Validation: Block All-Uppercase/All-Lowercase Entries

Great question—your current regex handles valid characters but misses the casing constraint. Let's fix that while keeping support for edge cases like d'Arras or de Clemente.

Core Requirement Recap

We need to:

  • Allow letters (any case, mixed), spaces, commas, dots, apostrophes, and hyphens
  • Block entries where all letters are uppercase (e.g., D'ARRAS, SMITH) or all letters are lowercase (e.g., de clemente, jones)

The Solution Regex

Here's a refined regex that meets these needs:

^(?![^A-Z]+$)(?![^a-z]+$)[a-z ,.'-]+$

Or, if you prefer using the case-insensitive (i) modifier (which makes the character class more readable):

^(?![a-z ,.'-]+$)(?![A-Z ,.'-]+$)[a-z ,.'-]+$

How It Works

Let's break down the key parts:

  • ^ and $: Anchor the regex to match the entire string (no partial matches)
  • (?![^A-Z]+$): Negative lookahead that ensures the string isn't entirely made of non-uppercase characters (i.e., there's at least one uppercase letter)
  • (?![^a-z]+$): Negative lookahead that ensures the string isn't entirely made of non-lowercase characters (i.e., there's at least one lowercase letter)
  • [a-z ,.'-]+: Matches all valid characters (letters, spaces, commas, dots, apostrophes, hyphens)

Test Cases

Valid (Will Pass)

  • d'Arras
  • de Clemente
  • O'Neil
  • van der Sar
  • De la Cruz

Invalid (Will Fail)

  • D'ARRAS (all letters uppercase)
  • de clemente (all letters lowercase)
  • SMITH (all uppercase)
  • jones (all lowercase)
  • 123Smith (contains invalid numeric characters)

Notes

  • If your use case allows single-letter surnames (e.g., X or x), this regex will reject them (since they can't have mixed casing). If you need to support these, you'd need to add an exception—just let me know!
  • The regex assumes symbols (spaces, commas, etc.) don't count toward casing checks, which aligns with standard surname formatting rules.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 11:37:28