Nikos Maravitsas

About Nikos Maravitsas

Nikos has graduated from the Department of Informatics and Telecommunications of The National and Kapodistrian University of Athens. 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.

How To Validate Hex Color Code With Regular Expression

In this tutorial we are going to see how to create a simple application that validates Hexadecimal Color Codes. The main policy abount Hex Color Codes denotes that it has to:

  • Start with ‘#’ tag.
  • Contain any lower case or uppercase characters from ‘a’ to ‘f’.
  • Contain digits from ‘0’ to ‘9’.
  • Have a length of 3 or 6 without including the ‘#’ tag.

 
 
 
So this is the regular expression we are going to use for hex color code validation:

^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$

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 hex color code validation.

HexColorValidator.java:

package com.javacodegeeks.java.core;

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

public class HexColorValidator {

	private Pattern pattern;
	private Matcher matcher;

	private static final String HEX_PATTERN = "^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$";

	public HexColorValidator() {
		pattern = Pattern.compile(HEX_PATTERN);
	}

	public boolean validate(final String hexColorCode) {

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

	}
}

2. Unit Testing our HexColorValidator 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 hex color codes.

This is a basic test class:

HexColorValidatorTest.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 HexColorValidatorTest {

	private String arg;
	private static HexColorValidator hexColorValidator;
	private Boolean expectedValidation;

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

	@BeforeClass
	public static void initialize() {
		hexColorValidator = new HexColorValidator();
	}

	@Parameters
	public static Collection<Object[]> data() {
		Object[][] data = new Object[][] {
				{"#FAFA",false },         // it's not either 6 or 3 characters long 
				{ "FAFAFA", false },      // it doesn't begin with a # tag
				{ "#abg*", false },       // g is not a valid character     

				// valid hex color codes

				{"#1a1aa1",true },                         
				{ "#BCBCBC", true },
				{ "#C99", true },
				{ "#009999", true } };

		return Arrays.asList(data);
	}

	@Test
	public void test() {
		Boolean res = hexColorValidator.validate(this.arg);
		String validv = (res) ? "valid" : "invalid";
		System.out.println("Hex Color Code "+arg+ " is " + validv);
		assertEquals("Result", this.expectedValidation, res);

	}

}

Output:

Hex Color Code #FAFA is invalid
Hex Color Code FAFAFA is invalid
Hex Color Code #abg* is invalid
Hex Color Code #1a1aa1 is valid
Hex Color Code #BCBCBC is valid
Hex Color Code #C99 is valid
Hex Color Code #009999 is valid

 
This was an example on how to validate Hex Color Code With Regular Expressions in Java.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

and many more ....

Examples Java Code Geeks and all content copyright © 2010-2015, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

Get ready to Rock!
To download the books, please verify your email address by following the instructions found on the email we just sent you.

THANK YOU!

Close