[SOLVED] Regex to allow user names only

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
User avatar
Jean-Yves
Forum Contributor
Posts: 148
Joined: Wed Jul 02, 2003 2:13 pm
Location: West Country, UK

[SOLVED] Regex to allow user names only

Post 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.
Last edited by Jean-Yves on Thu Jun 02, 2005 9:06 am, edited 1 time in total.
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post 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 :)
User avatar
Jean-Yves
Forum Contributor
Posts: 148
Joined: Wed Jul 02, 2003 2:13 pm
Location: West Country, UK

Post by Jean-Yves »

Many thanks :)
Post Reply