Forum Moderators: open

Message Too Old, No Replies

Regex match alphanumeric ONLY string

I'm stumped.

         

barns101

12:06 pm on Aug 14, 2006 (gmt 0)

10+ Year Member



I have searched the web and WebmasterWorld unsuccessfully to find a piece of JavaScript to perform a regex that matches only an alphanumeric string, plus underscores and hyphens (to check requested usernames when joining a site).

I have tried the following code and I'm sure that it's my logic that's incorrect:


var myRegxp = /([a-zA-Z0-9_-]+)$/;
if(myRegxp.test("a$n")==false)
{
alert( "Please enter a valid username." );
}

It will return false if a completely non-alphanumeric string is entered (e.g. '%'), but return positive if an alphanumeric string containing non-alphanumeric characters is entered (e.g. 'abc%' or 'abc%123').

Can anyone point out what's wrong?

Thanks in advance. :)

**** Edit ****
I tkink I fixed it by adding a caret at the beginning:


var myRegxp = /^([a-zA-Z0-9_-]+)$/;
if(myRegxp.test("a$n")==false)
{
alert( "Please enter a valid username." );
}

I'm surprised it took so long and I didn't find a code snippet like this on the net :o

coopster

12:46 am on Aug 20, 2006 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Actually that doesn't seem quite right, barns101. The caret at the beginning of a regex like that says it should "start with" as opposed to negation. Negation occurs within the character class (inside the brackets).

adni18

1:55 am on Aug 20, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



They're essentially the same, no? Because as long as he's got the $ at the end, it means to match the entire string, from beginning (^) to end ($), nothing else, right?

coopster

1:30 pm on Aug 21, 2006 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



You are indeed correct -- thanks for bringing that to my attention ;)