Java Regular Expression Validate Username Example

Validating a username is a very common requirement while designing and developing web application. This example will show you how to validate a username using Java regular expression.

How to validate username using Java regular expression?

There may be different requirements to validate username. This example covers most common requirement of them. Example requirements are as follows.

1) Username must be 8 to 20 characters in length
2) Username can only contain alphanumeric characters, numbers, underscore (_) and dot (.)
3) Username cannot start with underscore and dot

Let’s try to build the regular expression pattern for the above requirements. We want only alphanumeric characters so it should be a to z or A to Z. Numbers will between 0 to 9. In addition, we also want _ and . in allowed characters.

Here is the initial pattern as per the requirements.

Let’s try out our username regex pattern.


The first username “john” and “Smith19” are not valid because they contain only 4 and 7 characters respectively. “JamesBond@007” is not valid because it contains @ symbol which is not allowed. Every other usernames from above example are valid as per the pattern.

The last user name “_michael_clarke” is invalid as per our requirement but it turns out be valid as per our pattern. So looks like we are done with our first two requirements, but we are yet to implement the third one “username cannot start with underscore (_) or dot (.)”.

Let’s modify our username pattern a bit as follows.

Basically we want to check that at the start of the string we want only alphanumeric character as first character by specifying “^[a-zA-Z0-9]”, which can be followed by “a-zA-Z0-9_.” characters 7 to 20 times. Remember that we have already specified the first character separately, so {8,20} has been changed to {7,20} now.

Let’s try the new expression.


Before we conclude, let’s think about usernames like “a_____b__c”, “a._._._b”, “a_.b__.c”. These usernames are valid as per our defined requirements but in real world they might not. In short, underscore (_) and (.) cannot appear in sequence.

In order to satisfy this requirement we will have to change our pattern a bit to fix multiple subsequent appearance of underscore and dot. We will use negative lookahead for validating this like given below.

The pattern is same except for the first part “(?!.*[_.]{2})”. This is a negative lookahead expression which checks that there should not be any combination of characters out of [_.] in length of two (so that “..”, “._”, “_.” and “__” will be invalid).

And here is the final code.


See Also: How to validate password using Java regular expression

Let us know your views in the comments section below.

Want to learn quickly?
Try one of the many quizzes. I promise you will not be disappointed.