Your regex, ^[\w ]+$
, allows one or more of any combination of word characters \w
or spaces, included several spaces in a row or nothing but spaces. You don't want \w
either, because it matches "word" characters where for some reason "word" has been defined as including digits and underscores.
Try the following instead:
^[A-Za-z']+( [A-Za-z']+)*$
This will match:
^ beginning of string
[A-Za-z']+ one or more letters or apostrophe
( [A-Za-z']+)* zero or more instances of (a single space followed by
by one or more letters or apostrophe)
$ end of string
You didn't mention apostrophes, but I added it in to allow for names like O'Conner.
Note though that this excludes quite a few non-English names. Assuming you're validating people's names here I think you're better off just letting the user enter what they want to enter.