Forum Moderators: coopster

Message Too Old, No Replies

Regex to validate usernames

         

StickeR

3:13 pm on Jun 15, 2007 (gmt 0)

10+ Year Member



Ok, somewhile ago I used a regular expression which I found on the internet, to validate email addresses, works fine.

This time around I thought I could modify it, to validate usernames on characters (letters, numbers, - and _ only).

So i cooked up this script:


if (eregi('^[a-zA-Z0-9\_\-]$', $name)) {
echo 'Valid';
} else {
echo 'Invalid';
}

But whatever I enter as a name, it always gives invalid.
I thought I understood this regular expression thign, but appearantly not.
If anyone could clarify where I messed up, I'd appreciate it.

eelixduppy

3:50 pm on Jun 15, 2007 (gmt 0)



Try this as you pattern:

$pattern = "/^[a-zA-Z0-9_-]+$/";
if (eregi($pattern, $name)) {

StickeR

5:19 pm on Jun 15, 2007 (gmt 0)

10+ Year Member



Thanks, but no luck.

Tried both 'techniques', but it still comes up as Invalid.

The odd part is it ALWAYS comes up as Invalid, no matter what you enter as $name.
Entering: 'ASdF324' as $name give Invalid (though it should be valid)
Entering: '^@&#@#*(@#{}::><' as $name also give invalid (which should be correct( but shows the ELse isnt reversed or anything.)

coopster

11:47 am on Jun 18, 2007 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Get rid of the anchors and negate the character class (then reverse your logic) ...
if (eregi('[^a-zA-Z0-9\_\-]', $name)) { 
echo 'Invalid';
} else {
echo 'Valid';
}