PHP Developers Network
http://forums.devnetwork.net/

[SOLVED] Regex to allow user names only
http://forums.devnetwork.net/viewtopic.php?f=38&t=33941
Page 1 of 1

Author:  Jean-Yves [ Thu Jun 02, 2005 5:29 am ]
Post subject:  [SOLVED] Regex to allow user names only

Hi,

Could somebody tell me how to write a regular expression that covers the following rules for a user name:

Must be 5 to 15 characters in length, and may only contain letters, underscores and hyphens.

I would need this for Javascript and for PHP, so if they use a different pattern, please could you show me both.

I have tried, truly I have. I've got bits working, but never the whole. Regular expressions and me were clearly never destined to cohabit the same point in time and space in any meaningful way! :wink:

Many thanks in advance.

Author:  Chris Corbyn [ Thu Jun 02, 2005 6:09 am ]
Post subject: 

\w matches letters A-Z (upper and lowercase) and underscores so you just need that in a charcted class alogn with a hyphen with {5,15} for the length.
Use ^ and $ to constrain where the start and end parts are.
Syntax: [ Download ] [ Hide ]
$username1 = 'ipsy_dipsy'; //Woohoo

$username2 = 'i am a little st*r'; //Got spaces! Got * !



if (preg_match('/^ї\w-]{5,15}$/', $username1)) {

    echo $username1 .' is valid';

} else {

    echo $username1 .' is invalid';

}


and in javascript we use the test() method

Syntax: [ Download ] [ Hide ]
var username1 = 'ipsy_dipsy'; //Woohoo

var username2 = 'i am a little st*r'; //Got spaces! Got * !



var re = new RegExp('/^ї\\w-]{5,15}$/');



if (re.test(username1)) {

    alert(username1 +' is valid');

} else {

    alert(username1 +' is invalid');

}


Hope it helps :)

Author:  Jean-Yves [ Thu Jun 02, 2005 9:05 am ]
Post subject: 


Page 1 of 1 All times are UTC - 5 hours
Powered by phpBB® Forum Software © phpBB Group
http://www.phpbb.com/