What are your thoughts on validating a First Name?
I didn’t want to allow any value for fear a bad guy could use this as a security exploit. (Although since I am using Prepared Statements, that might be hard to do.)
Here is my current code…
// Validate First Name.
if (empty($trimmed['firstName'])){
$errors['firstName'] = 'Please enter your First Name.';
}else{
if (preg_match('#^[A-Z \\'.-]{2,20}$#i', $trimmed['firstName'])){
$firstName = $trimmed['firstName'];
}else{
$errors['firstName'] = 'First Name must be 2-20 characters (A-Z \\' . -)';
}
}
Is this too restrictive?
In the U.S. at least, this should pretty much cover everything…
Some 15 years ago I think some people in England tried to call their kind something like 1526jhl4hklh246l3j6 there may have been special characters in that aswell but I can’t remember. I don’t think they succeeded though So, your regex should pretty much cover anything besides insane British people
It would depend on what I was using their first name for, I see no harm in letting them type anything they like as it currently stands. Why do feel you need to restrict their first name, do you have cause?
You’re exactly right though, there is a happy medium, you just need to figure out what your happy medium is; then implement it.
You could use an optimistic filter, i.e. do checks against characters rather than for them.
I.e. if you detect any punctuation, double-spaces, numbers then fail - otherwise pass. Remember that hyphens (e.g. “ann-marie”) are valid. But no matter how much regex you throw in there, there’s no stopping them using semantically valid, yet culturally invalid, names - e.g. ‘DonaldDuck’. So in that respect I agree with Anthony, that sometimes restrictions are just inspiration for greater creativity.
As for security exploits, you’ll be fine with any string as far as I’m aware, as long as you aren’t really, really stupid and put it in exec() or something. Also remember to htmlspecialchars it on output, or they could inject HTML/JS - which is all they can do when they can’t touch the database code. Though on the subject, that reminds me a little of http://xkcd.com/327/