Reputation: 27
I am trying to create a regex to validate Full Names similar to linkedin, where
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
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 endUpvotes: 2
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 stringSee 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