Forum Moderators: coopster

Message Too Old, No Replies

validate user name

         

rysolag

3:07 am on Nov 11, 2004 (gmt 0)

10+ Year Member



hi

i need to validate the characters in a user name. what PHP function can i use to check if the user name has only letters, numbers and/or underscores.

thanks

orion_rus

8:02 am on Nov 11, 2004 (gmt 0)

10+ Year Member



There are many functions to check it, but i suggest you to check it with javascript before sending it to server

coopster

11:39 am on Nov 11, 2004 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



On the server-side I think you'll find the Regular Expression Functions (Perl-Compatible) [php.net] most handy. You will find some good Regular Expression resources in the Learning PHP - Books, Tutorials and Online Resources [webmasterworld.com] which is in the PHP Forum Library [webmasterworld.com].

dreamcatcher

1:20 pm on Nov 11, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You might also be able to use the character classes. For example, to check for letters and numbers you could try:

if (eregi("^[[:alnum:]]+$", $username))
{
return true;
}
else
{
return false;
}

Best to look at the links Coopster posted to get you started.

coopster

2:40 pm on Nov 11, 2004 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Good call, dreamcatcher.

Are you going to allow any blanks in the user names? Blanks will throw you for a loop, too. This example does not allow blanks:

$names = array('bad one', 'good_1', '', ' ', 'bad-one'); 
foreach ($names as $key => $name) {
// Bad names:
if (!$name or preg_match("/[^[:alnum:]_]/", $name)) print "$key: $name\n";
}
// Prints out the bad names:
0: badone
2:
3:
4: bad-one
Use this to play around and learn more about regular expressions. The tutorials in the links provided earlier will help you get a better grip on them. Daunting at first, but awesome once you get a grip on them.

dreamcatcher

4:21 pm on Nov 11, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Another useful thing to use is the trim() function to eliminate any white space when your data is posted.

Happy coding. :)