Page 1 of 1

[SOLVED] Regex to allow user names only

Posted: Thu Jun 02, 2005 5:29 am
by Jean-Yves
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.

Posted: Thu Jun 02, 2005 6:09 am
by Chris Corbyn
\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.

Code: Select all

$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

Code: Select all

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 :)

Posted: Thu Jun 02, 2005 9:05 am
by Jean-Yves
Many thanks :)