Validating a First Name

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…

Debbie

Some 15 years ago I think some people in England tried to call their kind something like 1526jhl4hklh246l3j6 :stuck_out_tongue: there may have been special characters in that aswell but I can’t remember. I don’t think they succeeded though :stuck_out_tongue: So, your regex should pretty much cover anything besides insane British people :smiley:

Rèmon? Sánchez?

So how would you handle things then?

If I open things up then some j4ck4ss will start typing “d3bb1e” and “rbrt” and “k8tee” and “!@#$%^&*()_+”

Do people with weird names like “Rèmon” know better to just enter “Remon”?? :wink:

There must be a happy-medium?!

Debbie

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. :slight_smile:

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/

So maybe I need to chill out on making people “proper” name?

As far as security, I am using Prepared Statements, and I believe that they catch everything so I should be safe there.

Is that correct?

Debbie

They don’t catch html and js. You should still filter those.