1

I am try to validate a form to make the user enter their full name like the following..

First, Last

The user must have some string of alphabetic only chars, then a comma, then a space, then a last name, which can again be any string of chars.

This is my current regex..

var alphaExp = /^[a-zA-Z,+ a-zA-Z]+$/;

However, it lets the user submit something as simple as john. I want it to force them to submit something such as john, smith.

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
  • 1
    So you only want to allow users to successfully fill your form, that have a single first name and a single last name of only alphanumeric characters? What about someone named "Raphael van der Vart", or "Shaquille O'Neel", or "Gerd Müller", or "Tim Bastián"? – crackmigg Nov 15 '12 at 20:24

4 Answers4

3

What you are doing is creating a character class ([]) that matches any of the following characters: a-zA-Z,+. This allows john to match the whole regex.

This is what you want:

/^[a-zA-Z]+, [a-zA-Z]+$/

However, I would like to advise you that making assumptions about names is a little wrong. What if some guy is named John O'Connor? Or Esteban Pérez? Or just Ng (only a first name)?

"Code that believes someone’s name can only contain certain characters is stupid, offensive, and wrong" - tchrist

Sure, you don't want to let people to enter just gibberish, but leave an option for users to enter something that doesn't necessarily fit your idea of correctness, but is nonetheless correct.

Community
  • 1
  • 1
NullUserException
  • 83,810
  • 28
  • 209
  • 234
  • 1
    There are a lot of wrong things programmers believe about names. Here's a good list of inaccurate assumptions for further reading: http://www.kalzumeus.com/2010/06/17/falsehoods-programmers-believe-about-names/ – Qsario Nov 15 '12 at 20:31
1

That's not how character sets work:

/^[a-zA-Z]+, [a-zA-Z]+$/

Things to consider:

  • Any validation you do on the client can be bypassed
  • Some people may have names with accented letters
  • Some cultures don't use just two names
Eric
  • 95,302
  • 53
  • 242
  • 374
0
^[a-zA-Z]+, [a-zA-Z]+$

Should work, however, do you want to prevent '.'? As in J. Hooker? And more words, like 'Jan van Hoogstrum'? Note also that you are preventing any accented characters being used. An option (although it allows underscores) is to use \w:

^(\w+ )$

Which would give you 'name name name...'. 'First, last' is not a common way to enter your name, so you'll frustrate a lot of users that way.

Phil H
  • 19,928
  • 7
  • 68
  • 105
0

The correct regexp for allowing only the first letter to be capital would be:

/^[A-Z][a-z]+, [A-Z][a-z]+$/

ro0ter
  • 439
  • 2
  • 11