tip2tail
tip2tail

Reputation: 463

Javascript RegEx not returning false as expected

Not a big user of RegEx - never really understood them! However, I feel the best way to check input for a username field would be with one that only allows Letters (upper or lower), numbers and the _ character, and must start with a letter as per the site policy. The My RegEx and code is as such:

var theCheck = /[a-zA-Z]|\d|_$/g;
alert(theCheck.test(theUsername));

Despite trying with various combinations, everything is returning "true".

Can anyone help?

Upvotes: 1

Views: 88

Answers (3)

jahroy
jahroy

Reputation: 22692

Use this as your regex:

^[A-Za-z][a-zA-Z0-9_]*$

Upvotes: 1

Justin Pihony
Justin Pihony

Reputation: 67135

How about something like this:

^([a-zA-Z][a-zA-Z0-9_]{3,})$

To explain the entire pattern:

^ = Makes sure that the first pattern in brackets is at the beginning
() = puts the entire pattern in a group in case you need to pull it out and not just validate
a-zA-Z0-9_ = matches your character allowances
$ = Makes sure that this must be the entire line
{3,} = Makes sure there are a minimum of 3 characters. 
    You can add a number after the comma for a character limit max
    You could also use a +, which would merely enforce at least one character match the second pattern. A * would not enforce any lengths

Upvotes: 3

gen_Eric
gen_Eric

Reputation: 227310

Your regex is saying "does theUsername contain a letter, digit, or end with underscore".

Try this instead:

var theCheck = /^[a-z]([a-z_\d]*)$/i; // the "i" is "ignore case"

This says "theUsername starts with a letter and only contains letters, digits, or underscores".

Note: I don't think you need the "g" here, that means "all matches". We just want to test the whole string.

Upvotes: 3

Related Questions