views:

268

answers:

2

I have a user registration form and I only want the user to specify their first and last name (i.e. Donalg Doonsberry). If the user doesn't provide their name in this fashion, the input will be rejected. I thought something like this would work for my regex user validation in cakephp:

  'name'=>array('Name has to be comprised of letters.
                '=>array('rule'=>array('custom', '/[A-Za-z ]+/')
           )),
+3  A: 

You have to be careful validating names... what about:

  • Donalg McDonald <- capital in the middle of a word
  • Donalg Fooble-Whiffery <- hyphenated
  • Donalg Déénsbnérry-McDonald Sr. 3rd <- you get the idea

To validate names in the format you specified:

/[A-Z][a-z]+ [A-Z][a-z]+/

Being a bit more lenient:

/([\w.-]+ )+[\w+.-]/
Greg
+1 I second the notion that trying to validate human names with regex is nonsense. I'm not even sure what that would be good for.
Tomalak
how do you validate that the user inputs data that is not malicious?
donalg d
You shouldn't need to - you should escape it properly every time you use it - either in an SQL query (e.g. mysql_real_escape_string) or outputting to a page (e.g. htmlspecialchars)
Greg
A: 

Personally, I wouldn't bother with first/last name validation. You can only validate their length (there is a built-in validation rule in cake for that) and make sure you put "allowEmpty" => true, if that's what you want.

dr Hannibal Lecter