Java regex validate username examples
This article shows how to use regex to validate a username in Java.
Username requirements
- Username consists of alphanumeric characters (a-zA-Z0-9), lowercase, or uppercase.
- Username allowed of the dot (.), underscore (_), and hyphen (-).
- The dot (.), underscore (_), or hyphen (-) must not be the first or last character.
- The dot (.), underscore (_), or hyphen (-) does not appear consecutively, e.g., java..regex
- The number of characters must be between 5 to 20.
Below is the regex that matches all the above requirements.
^[a-zA-Z0-9]([._-](?![._-])|[a-zA-Z0-9]){3,18}[a-zA-Z0-9]$
1. Username regex explanation
Below is the username regex explanation.
^[a-zA-Z0-9] # start with an alphanumeric character
( # start of (group 1)
[._-](?![._-]) # follow by a dot, hyphen, or underscore, negative lookahead to
# ensures dot, hyphen, and underscore does not appear consecutively
| # or
[a-zA-Z0-9] # an alphanumeric character
) # end of (group 1)
{3,18} # ensures the length of (group 1) between 3 and 18
[a-zA-Z0-9]$ # end with an alphanumeric character
# {3,18} plus the first and last alphanumeric characters,
# total length became {5,20}
What is ?!
The regex symbol ?!
is a negative lookahead, ensures something not followed by something else; for example, _(?!_)
ensures the underscore does not follow by an underscore.
2. Regex to validate username
Below is a Java example of using the above regex to validate a username.
package com.mkyong.regex.username;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class UsernameValidator {
// simple regex
//private static final String USERNAME_PATTERN = "^[a-z0-9\\._-]{5,20}$";
// strict regex
private static final String USERNAME_PATTERN =
"^[a-zA-Z0-9]([._-](?![._-])|[a-zA-Z0-9]){3,18}[a-zA-Z0-9]$";
private static final Pattern pattern = Pattern.compile(USERNAME_PATTERN);
public static boolean isValid(final String username) {
Matcher matcher = pattern.matcher(username);
return matcher.matches();
}
}
3. Username regex unit tests
Below are the unit tests to validate a list of valid and invalid usernames.
package com.mkyong.regex.username;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class UsernameValidatorTest {
@ParameterizedTest(name = "#{index} - Run test with username = {0}")
@MethodSource("validUsernameProvider")
void test_username_regex_valid(String username) {
assertTrue(UsernameValidator.isValid(username));
}
@ParameterizedTest(name = "#{index} - Run test with username = {0}")
@MethodSource("invalidUsernameProvider")
void test_username_regex_invalid(String username) {
assertFalse(UsernameValidator.isValid(username));
}
static Stream<String> validUsernameProvider() {
return Stream.of(
"mkyong",
"javaregex",
"JAVAregex",
"java.regex",
"java-regex",
"java_regex",
"java.regex.123",
"java-regex-123",
"java_regex_123",
"javaregex123",
"123456",
"java123",
"01234567890123456789");
}
static Stream<String> invalidUsernameProvider() {
return Stream.of(
"abc", // invalid length 3, length must between 5-20
"01234567890123456789a", // invalid length 21, length must between 5-20
"_javaregex_", // invalid start and last character
".javaregex.", // invalid start and last character
"-javaregex-", // invalid start and last character
"javaregex#$%@123", // invalid symbols, support dot, hyphen and underscore
"java..regex", // dot cant appear consecutively
"java--regex", // hyphen can't appear consecutively
"java__regex", // underscore can't appear consecutively
"java._regex", // dot and underscore can't appear consecutively
"java.-regex", // dot and hyphen can't appear consecutively
" ", // empty
""); // empty
}
}
All passed.
4. Anti-regex, Java username validator
Below is an equivalent Java code for anti-regex developers to validate a username (meets all the above username’s requirements).
package com.mkyong.regex.username;
public class UsernameValidatorCode {
private static final char[] SUPPORT_SYMBOLS_CHAR = {'.', '_', '-'};
public static boolean isValid(final String username) {
// check empty
if (username == null || username.length() == 0) {
return false;
}
// check length
if (username.length() < 5 || username.length() > 20) {
return false;
}
return isValidUsername(username.toCharArray());
}
private static boolean isValidUsername(final char[] username) {
int currentPosition = 0;
boolean valid = true;
// check char by char
for (char c : username) {
// if alphanumeric char, no need check, process next
if (!Character.isLetterOrDigit(c)) {
// for non-alphanumeric char, also not a supported symbol, break
if (!isSupportedSymbols(c)) {
valid = false;
break;
}
// ensures first and last char not a supported symbol
if (username[0] == c || username[username.length - 1] == c) {
valid = false;
break;
}
// ensure supported symbol does not appear consecutively
// is next position also a supported symbol?
if (isSupportedSymbols(username[currentPosition + 1])) {
valid = false;
break;
}
}
currentPosition++;
}
return valid;
}
private static boolean isSupportedSymbols(final char symbol) {
for (char temp : SUPPORT_SYMBOLS_CHAR) {
if (temp == symbol) {
return true;
}
}
return false;
}
}
The same #3 unit tests again, replace the regex validator with the above Java username validator, all tests passed.
Further Reading
If you are using email as username, try this Java email regex example
Download Source Code
$ git clone https://github.com/mkyong/core-java
$ cd java-regex/username
Hi,
Great Post.It make me great knowledge on Regular Expression.
Amazing!!
Seems like the ‘?’ should be outside the brackets or it’s just Golang
In java, matches() method match the whole string, then what is the use of caret(^) symbol in the expression?
Will it work without caret symbol in the expression?
i want to ask that wheather we can use special characters in userneme.?
yes, dot, hyphen and underscore are common special characters in username.
It is taking numeric values initially. for example 05john is not a valid username.
Depend on your requirements. For me, it is a valid username.
Wouldn’t a username of “___________” or “————-” pass this check? I’m pretty sure don’t want those if you’re going to be restrictive about which characters are okay.
Thanks for your feedback. We updated the regex to ensure special symbols cant appear consecutively, see username requirement #4.