kanayaki
kanayaki

Reputation:

How can I verify that user name starts with a letter and contains only alphanumeric characters?

I am using Jquery Validation.

Currently, I have a username, what i want to validate for this username is:

I am stuck at the last validation. How to write a regular expression to validate first character MUST be alphabet?

BTW:

The no whitespace seems having problem. I tried my script, 1 whitespace its allowed, but 2 whitespaces not allowed, why?

Upvotes: 1

Views: 19010

Answers (2)

Sinan Ünür
Sinan Ünür

Reputation: 118128

Use

/^[A-Za-z][A-Za-z0-9]+$/

for the alphanumeric method.

This matches any string which consists of a letter followed by one or more alphanumeric characters. This assumes that single character user names are not allowed. If you do want to allow single character user names, change the pattern to:

/^[A-Za-z][A-Za-z0-9]*$/

This way, there is no need for a separate check for the first character. Incidentally, this should also obviate the need for the whitespace check as a string that consists entirely of alphanumeric characters cannot contain any whitespace by definition.

Upvotes: 10

ChaosPandion
ChaosPandion

Reputation: 78262

value.substr(0, 1).match(/[A-Za-z]/) != null

Upvotes: 2

Related Questions