...

View Full Version : validate username w/ preg_match



700lbGorilla
09-23-2005, 01:22 AM
I'm new to the preg_match and haven't seen a good tutorial that really explains it to people that are completely new, example, me. I want to validate a username, it can contain lowercase, uppercase and and underscore. But it can't start or end with an underscore. So 700lbGorilla, 700lb_Gorilla, 700_lb_Gorilla are ok, but _700lbGorilla and 700lbGorilla_ are not.


preg_match('/^[a-zA-Z0-9][\w][a-zA-Z0-9]$/', $name)

But that didn't work to well, i'm pretty sure the first bracket is right, but after that I'm lost.

NancyJ
09-23-2005, 08:22 AM
preg_match('/^[a-zA-Z0-9][\w]+[a-zA-Z0-9]$/', $name)

you need to specify that they can have more than 1 \w ;)

700lbGorilla
09-23-2005, 03:22 PM
Thanks for the reply, I changed the + to a *. Than way if there isn't a _ it still is valid.

NancyJ
09-23-2005, 03:37 PM
\w is any character or digit... not just underscores

700lbGorilla
09-23-2005, 04:12 PM
I know I meant I used a * incase there is no \w. UNless I'm still lost and ther both do the same.

NancyJ
09-23-2005, 04:21 PM
^[a-zA-Z0-9][\w]+[a-zA-Z0-9]$ means
the first character must be a letter or a number, the next one or more characters can be any word character and the last character must be a number or letter.
Which means the string must be at least 3 characters long.

^[a-zA-Z0-9][\w]*[a-zA-Z0-9]$
means the first character must be a letter or number, the next zero or more characters can be any word character and the last character must be a number or letter.
Which means the string must be at least 2 characters long (the first and last)

700lbGorilla
09-23-2005, 04:29 PM
Ok, thank you, that clears it up.

700lbGorilla
09-23-2005, 11:04 PM
I really suck at this topic, wouldn't


if(eregi('/^[a-z]+$/'
be only lowercase letters?

marek_mar
09-23-2005, 11:14 PM
Yes. You could add an "i" at the end if you don't care about the case.

700lbGorilla
09-23-2005, 11:18 PM
if(!empty($fname)) {
if(eregi('/^[a-z]+$/', $fname)) {
$f = ucfirst(strtolower($fname));
} else {
$f = FALSE;
echo '<p><font color="red">Your name contains invalid characters.</font></p>';
}
} else {
$f = $fname;
}

Typing in "asdsd" comes out false.

marek_mar
09-24-2005, 11:41 AM
Try trim($fname) and then the regex.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum