1

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?

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Bonus, OP should search for common regex patterns. Pretty sure others have gone thru that pain
Does this force the first character to be a letter?
@tip2tail: It does now, it didn't before.
@Alfabravo - as I alluded to in my first post I'm really effin dumb when it comes to RegEx. I did search, copied and pasted for the last hour and a half but got nowhere fast. In 10 mins here I'm now light years ahead in terms of my project. Thanks tho! ;o)
3

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

2 Comments

Overkill in the length of the second block. A '+' should do (we don't know how long should it be)
@Alfabravo I am actually about to add some explanation. However, I would hope it would be at least 2+ characters
1

Use this as your regex:

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

3 Comments

Wouldn't that match a blank string?
Oh yeah... Oops. I also forgot about "it must start with a letter".
@jahroy BTW, this will not deal with the it must start with, and that the entire line must be correct

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.