Sam
Sam

Reputation: 2347

Regex to check if the first character is uppercase

I'm trying to check that the first character of a username is capital, the following can be letters or numbers and at most 20 characters long. Can someone explain why my syntax is wrong?

/^[A-z][a-z0-9_-]{3,19}$/

Upvotes: 19

Views: 82785

Answers (5)

Mateen Ulhaq
Mateen Ulhaq

Reputation: 27201

Why can't you let the poor users pick their own usernames? What you should do is convert all caps to lowercase.

"User Name".toLowerCase();

But if you are truly evil, you should change that z to a Z:

/^[A-Z][A-Za-z0-9_-]{3,19}$/

Upvotes: 10

BronzeByte
BronzeByte

Reputation: 725

I would do it like this:

var firstChar = strToCheck.substring(0, 1);

if (firstChar == firstChar.toUpperCase()) {
    // it is capital :D
}

Upvotes: 7

ipr101
ipr101

Reputation: 24236

You have a typo, the first z should be a capital -

/^[A-Z][a-z0-9_-]{3,19}$/

Upvotes: 0

BoltClock
BoltClock

Reputation: 723498

Your first Z is not a capital Z.

/^[A-Z][a-z0-9_-]{3,19}$/

Upvotes: 32

Adam Rackis
Adam Rackis

Reputation: 83358

Your first character needs to be A-Z, not A-z

So

/^[A-z][a-z0-9_-]{3,19}$/

Should be

/^[A-Z][a-z0-9_-]{3,19}$/

Upvotes: 6

Related Questions