Moshappp
Moshappp

Reputation: 27

How to regex match Full Name like Linkedin

I am trying to create a regex to validate Full Names similar to linkedin, where

  1. Only letters at the beginning of the string
  2. The string can contain letters, dots, hyphens, and spaces
  3. The string cannot start with dots, hyphens, or spaces
  4. Dots, hyphens, and spaces can only appear between letters and not be consecutive.
  5. The string can end with one dot
  6. No dots, hyphens are allowed after a space

For Example(Valid):

For Example(NOT Valid):

I tried to implement this, it is pretty similar what I want to achieve but matches cases that should be invalid, like the string 'John..Doe.'

/^[a-zA-Z]+([a-zA-Z\s.-]*[a-zA-Z]+)*(\.\s*[a-zA-Z]*)?$/

Upvotes: 0

Views: 172

Answers (2)

Peter Thoeny
Peter Thoeny

Reputation: 7616

Here is a regex that will validate names as per your requirements:

const regex = /^(?:[a-z]+[.-]? ?)+[a-z]+\.?$/i;
[
  'John. Doe.',
  'JAane John Doe',
  'Jane John Doe.',
  'Jane John.Doe',
  'Jane John-Doe',
  'Jane John-Doe.',
  '.John',
  'John-',
  'John-',
  'John .Doe',
  'John -Doe',
  'John--Doe',
  'John..Doe',
  'John.-Doe',
].forEach(name => {
  console.log(name, '==>', regex.test(name));
});

Output:

John. Doe. ==> true
JAane John Doe ==> true
Jane John Doe. ==> true
Jane John.Doe ==> true
Jane John-Doe ==> true
Jane John-Doe. ==> true
.John ==> false
John- ==> false
John- ==> false
John .Doe ==> false
John -Doe ==> false
John--Doe ==> false
John..Doe ==> false
John.-Doe ==> false

Explanation of regex:

  • ^ -- anchor at start
  • (?: -- start non-capture group
    • [a-z]+ -- 1+ alpha chars
    • [.-]? ? -- optional dot or dash, followed by optional space
  • )+ -- end non-capture group
  • [a-z]+ -- 1+ alpha chars
  • \.? -- optional dot
  • $ -- anchor at end

Upvotes: 2

The fourth bird
The fourth bird

Reputation: 163517

Another option is to rule out what is not allowed after matching the first char a-z

^[a-z](?!.*?([ .-][.-]|  |-$))[a-z .-]*$
  • ^ Start of string
  • [a-z] Match a char a-z
  • (?! Negative lookahead, assert that to the right is not
    • .*? Match any character except a newline, as few as possible
    • ([ .-][.-]| |-$) Match either 2 consecutive characters out of [ .-][.-] or 2 spaces or - at the end of the string
  • ) Close the negative lookahead
  • [a-z .-]* Match optional listed allowed chars
  • $ End of string

See a regex101 demo.

const regex = /^[a-z](?!.*?([ .-][.-]|  |-$))[a-z .-]*$/i;
[
  'John. Doe.',
  'JAane John Doe',
  'Jane John Doe.',
  'Jane John.Doe',
  'Jane John-Doe',
  'Jane John-Doe.',
  '.John',
  'John-',
  'John-',
  'John .Doe',
  'John -Doe',
  'John--Doe',
  'John..Doe',
  'John.-Doe'
].forEach(s =>
  console.log(s, '-->', regex.test(s))
);

Upvotes: 0

Related Questions