js999
js999

Reputation: 2083

regexp for checking the full name

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

Answers (6)

deldev
deldev

Reputation: 1376

This version allows accented characters and works fine for me!

^([a-zA-Zà-úÀ-Ú]{2,})+\s+([a-zA-Zà-úÀ-Ú\s]{2,})+$

Upvotes: 2

jam_es
jam_es

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

/^[a-zA-Z]+(([',. -][a-zA-Z ])?[a-zA-Z]*)*$/g

Upvotes: 1

This answer also supports unicode characters.

^[\p{L}]([-']?[\p{L}]+)*( [\p{L}]([-']?[\p{L}]+)*)+$

Upvotes: 1

dlras2
dlras2

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

Mitya
Mitya

Reputation: 34556

A couple of points:

  1. 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).

  2. If you do use the constructor, in the case of RegExp you don't need the delimiting forward slashes

  3. Your current pattern matches only the first word

  4. {1,} can be written with the modifier +

Try

/^([a-z']+(-| )?)+$/i

Note the surname allows for double-barrel surnames.

Upvotes: -1

Related Questions