user1259167
user1259167

Reputation: 447

Name validation - Adding a check to this regex to stop entering just identical characters

I'm trying to add another feature to a regex which is trying to validate names (first or last).

At the moment it looks like this:

/^(?!^mr$|^mrs$|^ms$|^miss$|^dr$|^mr-mrs$)([a-z][a-z'-]{1,})$/i

https://regex101.com/r/pQ1tP2/1

The idea is to do the following

I have managed to get this far (shockingly I find regex so confusing lol).

It matches things like O'Brian or Anne-Marie etc and is doing a pretty good job.

My next additions I've struggled with though! trying to add additional features to the regex to not match on the following:

Thanks :)

Upvotes: 0

Views: 88

Answers (1)

Aaron
Aaron

Reputation: 24812

I'd add another negative lookahead alternative matching against ^(.)\1*$, that is, any character, repetead until the end of the string.
Included as is in your regex, it would make that :

/^(?!^mr$|^mrs$|^ms$|^miss$|^dr$|^mr-mrs$|^(.)\1*$)([a-z][a-z'-]{1,})$/i

However, I would probably simplify your negative lookahead as follows :

/^(?!(mr|ms|miss|dr|mr-mrs|(.)\2*)$)([a-z][a-z'-]{1,})$/i

The modifications are as follow :

  • We're evaluating the lookahead at the start of the string, as indicated by the ^ preceding it : no need to repeat that we match the start of the string in its clauses
  • Each alternative match the end of the string. We can put the alternatives in a group, which will be followed by the end-of-string anchor
  • We have created a new group, which we have to take into account in our back-reference : to reference the same group, it now must address \2 rather than \1. An alternative in certain regex flavours would have been to use a non-capturing group (?:...)

Upvotes: 2

Related Questions