Forum Moderators: coopster

Message Too Old, No Replies

Help validating username

         

adammc

12:01 am on Apr 9, 2007 (gmt 0)

10+ Year Member



Hi guys,

I am trying to validate a username input on my form using regular expression.

The username can only have letters, numbers, underscores a single period. I dont want them to be able to use spaces and caps (possibly converting all chars to lowercase?)

Can anyone help?

eelixduppy

12:11 am on Apr 9, 2007 (gmt 0)



Try something like this:

$pattern = "/^([a-z0-9._])+$/";
if(![url=http://www.php.net/preg-match]preg_match[/url]($pattern,$username)) {
echo 'Username contains invalid characters!';
} else {
echo 'Username is good!';
}

Refer to Pattern Syntax [php.net] for more information. :)

adammc

12:36 am on Apr 9, 2007 (gmt 0)

10+ Year Member



Hi eelixpuppy,

Thanks for the reply :)
So the code below would do everything I mentioned in my first post?

// check for a valid username

$pattern = "/^([a-z0-9._])+$/";
if(!preg_match($pattern,$username)) {
$errors[] = 'Please enter your first name';
} else {
// if it passes validation, convert to lowercase
$username = strtolower($username);

}

eelixduppy

12:40 am on Apr 9, 2007 (gmt 0)



Yes, however, you don't have to convert it to lowercase because the pattern already checks for that. If you want, to save the user some work (just in case they do type in a capital letter, it will reject it, but it could be perfectly fine otherwise) you can allow uppercase in the pattern and then convert it to lowercase like you have it. In that case, the new pattern would be like this:

$pattern = "/^([a-zA-Z0-9._])+$/";

Btw, you should really try the code out to check it. I haven't tested it ;)

adammc

12:47 am on Apr 9, 2007 (gmt 0)

10+ Year Member



Whoo Hoo! That did the trick :)
Thank you so much for your help.

One last question if you don't mind?
How would I disallow usernames over '20' chars?

eelixduppy

12:50 am on Apr 9, 2007 (gmt 0)




if(!preg_match($pattern,$username) ¦¦ ([url=http://www.php.net/strlen]strlen[/url]($username)>20)) {

;)

adammc

1:33 am on Apr 9, 2007 (gmt 0)

10+ Year Member



Getting Tsring errors :(

if(!preg_match($pattern,$_POST['username']) ¦¦ (strlen($_POST['username'])>20)) {
$errors[] = 'Please enter a valid username.';
} else {
// if it passes validation, convert to lowercase
$username = strtolower($username);
}

Any ideas?

adammc

1:35 am on Apr 9, 2007 (gmt 0)

10+ Year Member



Figured it out, it was the '¦'

eelixduppy

1:37 am on Apr 9, 2007 (gmt 0)



hehe, yes. WebmasterWorld breaks the pipe character and it must be replaced if you are going to copy and paste code from the browser. Glad you got everything sorted out :)

adammc

1:40 am on Apr 9, 2007 (gmt 0)

10+ Year Member



thanx again :)