How to validate username with regular expression

Username Regular Expression Pattern


^[a-z0-9_-]{3,15}$

Description


^                    # Start of the line
  [a-z0-9_-]	     # Match characters and symbols in the list, a-z, 0-9, underscore, hyphen
             {3,15}  # Length at least 3 characters and maximum length of 15 
$                    # End of the line

Whole combination is means, 3 to 15 characters with any lower case character, digit or special symbol “_-” only. This is common username pattern that’s widely use in different websites.

1. Java Regular Expression Example

UsernameValidator.java

package com.mkyong.regex;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class UsernameValidator{
	
	  private Pattern pattern;
	  private Matcher matcher;
 
	  private static final String USERNAME_PATTERN = "^[a-z0-9_-]{3,15}$";
	  
	  public UsernameValidator(){
		  pattern = Pattern.compile(USERNAME_PATTERN);
	  }
	  
	  /**
	   * Validate username with regular expression
	   * @param username username for validation
	   * @return true valid username, false invalid username
	   */
	  public boolean validate(final String username){
		  
		  matcher = pattern.matcher(username);
		  return matcher.matches();
	    	    
	  }
}

2. Username that match:

1. mkyong34
2. mkyong_2002
3. mkyong-2002
4. mk3-4_yong

3. Username that doesn’t match:

1. mk (too short, min 3 characters)
2. mk@yong (“@” character is not allow)
3. mkyong123456789_- (too long, max characters of 15)

4. Unit Test – UsernameValidator

Using testNG to perform unit test.

UsernameValidatorTest.java

package com.mkyong.regex;

import org.testng.Assert;
import org.testng.annotations.*;
 
/**
 * Username validator Testing
 * @author mkyong
 *
 */
public class UsernameValidatorTest {
 
	private UsernameValidator usernameValidator;
    
	@BeforeClass
        public void initData(){
		usernameValidator = new UsernameValidator();
        }
    
	@DataProvider
	public Object[][] ValidUsernameProvider() {
		return new Object[][]{
		   {new String[] {
	             "mkyong34", "mkyong_2002","mkyong-2002" ,"mk3-4_yong"
		   }}
      	        };
	}
	
	@DataProvider
	public Object[][] InvalidUsernameProvider() {
		return new Object[][]{
		   {new String[] {
		     "mk","mk@yong","mkyong123456789_-"	  
		   }}
	        };
	}
	
	@Test(dataProvider = "ValidUsernameProvider")
	public void ValidUsernameTest(String[] Username) {
		
	   for(String temp : Username){
		boolean valid = usernameValidator.validate(temp);
		System.out.println("Username is valid : " + temp + " , " + valid);
		Assert.assertEquals(true, valid);
	   }
	   
	}
	
	@Test(dataProvider = "InvalidUsernameProvider", 
                 dependsOnMethods="ValidUsernameTest")
	public void InValidUsernameTest(String[] Username) {
		
	   for(String temp : Username){
		boolean valid = usernameValidator.validate(temp);
		System.out.println("username is valid : " + temp + " , " + valid);
		Assert.assertEquals(false, valid);
	   }
	   
	}	
}

5. Unit Test – Result


Username is valid : mkyong34 , true
Username is valid : mkyong_2002 , true
Username is valid : mkyong-2002 , true
Username is valid : mk3-4_yong , true
username is valid : mk , false
username is valid : mk@yong , false
username is valid : mkyong123456789_- , false
PASSED: ValidUsernameTest([Ljava.lang.String;@1d4c61c)
PASSED: InValidUsernameTest([Ljava.lang.String;@116471f)

===============================================
    com.mkyong.regex.UsernameValidatorTest
    Tests run: 2, Failures: 0, Skips: 0
===============================================


===============================================
mkyong
Total tests run: 2, Failures: 0, Skips: 0
===============================================

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

Leave a Reply

avatar
newest oldest most voted
mike
Guest
mike

You da man mkyong

Omi
Guest
Omi

Thanks a lot!

maqsoodshah
Guest
maqsoodshah

hy pleez tell me i erning thi mony

mona
Guest
mona

i want to ask that wheather we can use special characters in userneme.?

maqsoodshah
Guest
maqsoodshah

pleez teel i want erion the mony

mona
Guest
mona

thanks

asif
Guest
asif

Hy
Thanx…very helpfull for me.

VMan
Guest
VMan

what can be the regex for /abc12/def23/ghi32 …… from 1 to many such text inside slash.

Manoj Sawant
Guest
Manoj Sawant

Hi,
Try following one, it works for me.
String regex = “/+[a-z]{3}[0-9]{2}”

Explanation :
– / # Excaped Character, Matches (/), charcode-47,
– {3} # Matches 3 characters of preceding token[a-z],
– {2} # Matches 2 characters of preceding token[0-9].

Hans
Guest
Hans

did you try __________ ?

immanuel G
Guest
immanuel G

What About full name..where User must type in two names.. can it look like this ..[A-Za-z]{2,}

krish
Guest
krish

thanks ur page s really nice …. and good ..!

Ramesh Deora
Guest
Ramesh Deora

It is taking numeric values initially. for example 05john is not a valid username.

chandu
Guest
chandu

nice tutorial..
Thanks

mthang86
Guest
mthang86

great topic,
thanks for your topic

trackback
Wicket textbox example

[…] Validate username with regular expression […]

Spencer Drager
Guest
Spencer Drager

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.

ajeet7171
Guest
ajeet7171

thanxx
nice tutorial

trackback
Java Regular Expression Tutorials | Tutorials

[…] Username regular expression Username regular expression example in Java and unit tested with TestNG. ^[a-z0-9_-]{3,15}$ […]

Muneeswaran
Guest
Muneeswaran

Hi,
Great Post.It make me great knowledge on Regular Expression.

trackback
10 Java Regular Expression Examples You Should Know | Regular Expressions

[…] ==> See the explanation and example here […]