Jon Spencer
Jon Spencer

Reputation: 21

How to modify this JavaScript regex to check for a person's valid name?

This JavaScript regex checks to see if a person has entered a valid username:

var regexp = "/^[a-z]([0-9a-z])+$/i";
if(!regexp.test(name)) 
  return "Name may consist of letter, numbers and start with a letter." );

But I want to check whether the person has entered a valid name.

In other words:

Cher
Michael Jackson
Mary J. Blige
François Truffaut

I can't think of any cases where anything other than letters and maybe a period would be valid in a person's name.

I want to reject any other types of punctuation as a validation mistake.

But I want to make sure that, for example, François Truffaut would not be rejected because he has that funny version of the letter c that the French use.

How would I do this in a Javascript regex

Upvotes: 2

Views: 1337

Answers (3)

detunized
detunized

Reputation: 15299

Try [\d\w.]+. It should take care of those funny French characters. Test it here online (it's for ruby, but it's almost the same).

[\d\w.][\d\w. ]*[\d\w.] would take the full name, including possible spaces in the middle. Limits the name length to two though. But it should be ok.

Upvotes: 1

Andrew Revak
Andrew Revak

Reputation: 441

Why not try to disallow just the punctuation you don't want in the name, probably a shorter list.

var regexp = "/^[\\\/$&^!@#%*~\?\[\]=\_\(\)]/"

That may not be a complete list but it should be a short list. These were the ones that seemed, the most reasonable IMO.

Upvotes: 4

simshaun
simshaun

Reputation: 21476

Enforcing character restraints on a name is a bad idea.

Upvotes: -1

Related Questions