MatcherPattern

Validate Username with Java Regular Expression example

When you are writing an application that requires authentication, in most cases, the users should provide a username among other credentials. It’s a very common security directive to perform an input validation on the credentials the users give. This is crucial for the security of your application and the consistency of your data in the application level of your system.

A good practice is to denote a policy about the format the usernames should have. And one of the most common ways to do that is via regular expressions.
 
 
 
 
In our example we want the username to be:

  • Between 2 and 25 characters long.
  • We want to contain characters, numbers and the ., -, _ symbols.

So the regular expression we should use will be

^[a-z0-9._-]{2,25}$

You can take a look at the Pattern class documentation to learn how to construct your own regular expressions according to your policy.

1. Validator class

This is the class that we are going to use for username validation.

UsernameValidator.java:

package com.javacodegeeks.java.core;

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._-]{2,25}$";

	  public UsernameValidator(){
		  this.pattern = Pattern.compile(USERNAME_PATTERN);
	  }

	  public boolean validate(final String password){

		  matcher = pattern.matcher(password);
		  return matcher.matches();

	  }
}

2. Unit Testing our UsernameValidator class

For unit testing we are going to use JUnit. Unit testing is very important in these situations because they provide good feedback about the correctness of our regular expressions. You can test your program and reassure that your regular expression meets the rules on your policy about the form of the usernames. For example, you might have a black list of usernames that you don’t want to have to your system, You cant test your validator against these values to see how it responds.

This is a basic test class:

UsernameValidatorTest.java:

package com.javacodegeeks.java.core;

import static org.junit.Assert.*;

import java.util.Arrays;
import java.util.Collection;

import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

@RunWith(Parameterized.class)
public class UsernameValidatorTest {

	private static String arg;
	private static UsernameValidator usernameValidator;
    private Boolean expectedValidation;

	public UsernameValidatorTest(String str, Boolean expectedValidation){
		this.arg = str;
		this.expectedValidation = expectedValidation;

	}

	@BeforeClass
	public static void initialize() {
		usernameValidator = new UsernameValidator();
	}

	@Parameters
	public static Collection<Object[]> data() {
		Object[][] data = new Object[][] { 
			{ "ascaefghfdghdfhdfghdfghdfhdfghdfghdfghdfghdfghdfghdfghdfghdfghdfghvavasv",false },
			{ "gregory.mar_james-law",true }, 
			{ "n!k1",false } ,
	 	        { "f",false    } };
		return Arrays.asList(data);
	}

	@Test
	public void test() {
		assertEquals("Result", this.expectedValidation, usernameValidator.validate(this.arg));

	}

}

If you run this test, you will see that all 4 tests run OK.
 
This was an example on how to validate username with Java Regular Expression.

Nikos Maravitsas

Nikos has graduated from the Department of Informatics and Telecommunications of The National and Kapodistrian University of Athens. During his studies he discovered his interests about software development and he has successfully completed numerous assignments in a variety of fields. Currently, his main interests are system’s security, parallel systems, artificial intelligence, operating systems, system programming, telecommunications, web applications, human – machine interaction and mobile development.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button