i have a regex ^[a-zA-Z0-9]{0,14}$ which will allow only alphanumerics. but there is problem i dont want a username to be only numbers and this regex is accepting only numbers also like 56426542 so how to restrict only numbers
Asked
Active
Viewed 3,268 times
3
-
I believe this will help: http://stackoverflow.com/questions/1221985/how-to-validate-a-user-name-with-regex – Christopher Bales Oct 01 '12 at 18:49
-
the problem is white spaces should not be there. it is not good to have white spaces.how to avoid that? – aquib.qureshi Oct 01 '12 at 18:51
-
1Do you have to do it with a single regex? Writing a few lines more can make your code more readable. – L.B Oct 01 '12 at 19:01
-
You probably don't want {0,14} - I would think a user name needs to be at least one character long. – Wonko the Sane Oct 01 '12 at 19:05
2 Answers
3
The regex you want:
^((?=.*[a-zA-Z])[a-zA-Z0-9]{0,14})$
Regex sandbox to play in with it.
This won't force you to have to start with a letter. The username can start with a letter or a number, an ensures that the username isn't only numbers.
Edit: fixed the length check. Also, you might want to change the {0,14} to {1,14}. Well, replace the first number with your minimum length requirement.

Gromer
- 9,861
- 4
- 34
- 55
-
The only problem with this is that it no longer restricts the length to 14 chars – Jeffrey Blake Oct 01 '12 at 18:59
-
No problem! I actually used one of the sample patterns from this Regex Cheat Sheet: http://www.addedbytes.com/cheat-sheets/regular-expressions-cheat-sheet/. The Password strength one. Great resource, at least for me. – Gromer Oct 01 '12 at 19:30
1
TIMTOWTDI
The simpliest solution is to require a username to start with a letter
^[A-Za-z][A-Za-z0-9]{0,14}
Keep in mind that {0,14} accepts empty string as a valid input
Edit
The previous expression accepts 1 to 15 characters of input a little better solution is:^[A-Za-z][A-Za-z0-9]{0,13}
But Grommer solution is better

rbernabe
- 1,062
- 8
- 10