24

I'm using regex to validate username

^[a-zA-Z]+\.[a-zA-Z]{4,10}^'

Unfortunately it doesn't affect if the the value contains special characters such as !@#$%^&*)(':;

I would glad to get some help for Regex that contains:

  • Alphanumeric only (a-zA-Z0-9)
  • Length between 4 - 10 characters.
3
  • What do you mean by 'Unfortunately it doesn't affect if the the value contains special characters'? The regexp that you posted shouldn't allow special characters. (Btw, what language are you using?)
    – Kaj
    Jul 25, 2011 at 10:37
  • 1
    .. and did you try to search the forum? stackoverflow.com/questions/5609243/regex-to-validate-username
    – Kaj
    Jul 25, 2011 at 10:39
  • So you don't want to support Unicode usernames?
    – Ken D
    Jul 25, 2011 at 10:45

2 Answers 2

53

The conditions you specified do not conform to the regexp you posted.

the regexp you posted ^[a-zA-Z]+\.[a-zA-Z]{4,10}^ is erroneous I guess, because of the ^ in the end, it will never be matched to any expression, if you want to match with the ^ at the end of the expression, you need to escape it like this \^. but ^ alone means "here is the start of the expression", while $ means "here is the end of the expression".

Even though, it denotes:

  • It starts with alpha (at least 1).
  • there must be a '.' period character.
  • Now there must be at least 4 alphas.

The regexp you need is really is:

^[a-zA-Z0-9]{4,10}$

This says:

  • It starts with alphanumeric.
  • There can be a minimum of 4 and a maximum of 10 alphanumeric.
  • End of expression.
5
  • Thanks but for example, the input !username I receive true from the regex
    – user330885
    Jul 25, 2011 at 11:07
  • 1
    Nope, go to regexpal.com and put ^[a-zA-Z0-9]{4,10}$ within the 1st box and !username in the 2nd, see? it is not yellowish, change it to username it is. What language do you use anyway?
    – Ken D
    Jul 25, 2011 at 11:13
  • 1
    Thanks, PHP - preg_match('/^[a-zA-Z0-9]{4,10}$/', $username);
    – user330885
    Jul 25, 2011 at 11:16
  • 1
    @Guy Dor, Here is a PHP Regular Expression test website, try to test username and !username and see the difference. P.S: I tried both of POSIX and PCRE, they gave the same result.
    – Ken D
    Jul 25, 2011 at 13:11
  • So ^[a-zA-Z0-9]$ would be no special characters, any length? Mar 29, 2017 at 21:05
8

Try this:

^[a-zA-Z0-9]{4,10}$