Reputation: 2083
I would like to write a regexp to check if the user inserted at least two words separated by at least one empty space:
Example:
var regexp = new RegExp(/^[a-z,',-]+(\s)[a-z,',-]+$/i);
regexp.test("D'avid Camp-Bel"); // true
regexp.test("John ---"); // true // but it should be false!
Upvotes: 14
Views: 29217
Reputation: 1376
This version allows accented characters and works fine for me!
^([a-zA-Zà-úÀ-Ú]{2,})+\s+([a-zA-Zà-úÀ-Ú\s]{2,})+$
Upvotes: 2
Reputation: 161
Simpler version
/^([\w]{3,})+\s+([\w\s]{3,})+$/i
([\w]{3,}) the first name should contain only letters and of length 3 or more
+\s the first name should be followed by a space
+([\w\s]{3,})+ the second name should contain only letters of length 3 or more and can be followed by other names or not
/i ignores the case of the letters. Can be uppercase or lowercase letters
Upvotes: 7
Reputation: 19
This answer also supports unicode characters.
^[\p{L}]([-']?[\p{L}]+)*( [\p{L}]([-']?[\p{L}]+)*)+$
Upvotes: 1
Reputation: 8486
Does ^[a-z]([-']?[a-z]+)*( [a-z]([-']?[a-z]+)*)+$
work for you?
[a-z]
ensures that a name always starts with a letter, then [-']?[a-z]+
allows for a seperating character as long as it's followed by at least another letter. *
allows for any number of these parts.
The second half, ( [a-z]([-']?[a-z]+)*)
matches a space followed by another name of the same pattern. +
makes sure at least one additional name is present, but allows for more. ({1,2}
could be used if you want to allow only two or three part names.
Upvotes: 26
Reputation: 34556
A couple of points:
In JavaScript it's generally better to use literals rather than named constructors (so /pattern/
rather than new RegExp()
. (Sure, there are times when you need the constructor route).
If you do use the constructor, in the case of RegExp you don't need the delimiting forward slashes
Your current pattern matches only the first word
{1,}
can be written with the modifier +
Try
/^([a-z']+(-| )?)+$/i
Note the surname allows for double-barrel surnames.
Upvotes: -1