Home » Core Java » util » regex » Matcher » Validate Image File Extension with Java Regular Expression example

About Nikos Maravitsas

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.

Validate Image File Extension with Java Regular Expression example

In this tutorial we are going to see how to validate image file format with Java Regular Expressions. This is vary userful for example when you create an image uploader and you want to make sure that the user does not upload an illegal file to your system. Of cource this is one of many countermesures you should consider. The basic policy about the fromat of image file is that:

  • It should begin with a string of a least one character and not a white space.
  • It must the be followed by dot ‘.’
  • And finally it should have one of the following file extensions : bmp, jpg, gif, png.

So this is the regular expression we are going to use for image file format validation:

([^\\s]+(\\.(?i)(/bmp|jpg|gif|png))$)

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 clas.

This is the class that we are going to use for image file format validation.

ImageFormatValidator.java:

package com.javacodegeeks.java.core;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
public class ImageFormatValidator{
 
   private Pattern pattern;
   private Matcher matcher;
 
   private static final String IMAGE_PATTERN = 
                "([^\\s]+(\\.(?i)(/bmp|jpg|gif|png))$)";
 
   public ImageFormatValidator(){
	  pattern = Pattern.compile(IMAGE_PATTERN);
   }
 
   public boolean validate(final String image){
 
	  matcher = pattern.matcher(image);
	  return matcher.matches();
 
   }
}

2. Unit Testing our ImageFormatValidator 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 image files.

This is a basic test class:

ImageFormatValidatorTest.java:

package com.javacodegeeks.java.core;

import static org.junit.Assert.assertEquals;

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 ImageFormatValidatorTest {

	private Boolean expectedValidationVlue;
	private static ImageFormatValidator imageFormatValidator;
	private String value;


	public ImageFormatValidatorTest(String str, Boolean expectedValue) {
		this.expectedValidationVlue = expectedValue;
		this.value = str;
	}

	@BeforeClass
	public static void initialize() {
		imageFormatValidator = new ImageFormatValidator();
	}

	@Parameters
	public static Collection<Object[]> data() {
		Object[][] data = new Object[][] {

				{"im.jpg", true},
				{"im.JPG", true},
				{"im.Jpg", true},
				{"im.Jpg", true},
				{"im.png", true},
				{"im.PNG", true},
				{"im.PnG", true},
				{"..PnG", true},
				{"im.GIF", true},
				{"im.GiF", true},
				{"im.gif", true},
				
				// image files that don't match
				
				{"im", false},
				{".JPG", false},
				{"i.sh", false},
				{"im.php", false},
				{"im.bin", false}
			
				
				
				
		};

		return Arrays.asList(data);
	}

	@Test
	public void test() {

		Boolean res = imageFormatValidator.validate(this.value);
		String validv = (res) ? "valid" : "invalid";
		System.out.println("Image File Format " + this.value + " is " + validv);
		assertEquals("Result", this.expectedValidationVlue, res);

	}

}

Output:

Image File Format im.jpg is valid
Image File Format im.JPG is valid
Image File Format im.Jpg is valid
Image File Format im.Jpg is valid
Image File Format im.png is valid
Image File Format im.PNG is valid
Image File Format im.PnG is valid
Image File Format ..PnG is valid
Image File Format im.GIF is valid
Image File Format im.GiF is valid
Image File Format im.gif is valid
Image File Format im is invalid
Image File Format .JPG is invalid
Image File Format i.sh is invalid
Image File Format im.php is invalid
Image File Format im.bin is invalid

 
This was an exampl on how to validate Image File Extension with Java Regular Expression.

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

 

Do you want to know how to develop your skillset and become a ...

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