How to validate email address with regular expression

Email Regular Expression Pattern


^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*
      @[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$;

Description


^			#start of the line
  [_A-Za-z0-9-\\+]+	#  must start with string in the bracket [ ], must contains one or more (+)
  (			#   start of group #1
    \\.[_A-Za-z0-9-]+	#     follow by a dot "." and string in the bracket [ ], must contains one or more (+)
  )*			#   end of group #1, this group is optional (*)
    @			#     must contains a "@" symbol
     [A-Za-z0-9-]+      #       follow by string in the bracket [ ], must contains one or more (+)
      (			#         start of group #2 - first level TLD checking
       \\.[A-Za-z0-9]+  #           follow by a dot "." and string in the bracket [ ], must contains one or more (+)
      )*		#         end of group #2, this group is optional (*)
      (			#         start of group #3 - second level TLD checking
       \\.[A-Za-z]{2,}  #           follow by a dot "." and string in the bracket [ ], with minimum length of 2
      )			#         end of group #3
$			#end of the line

The combination means, email address must start with “_A-Za-z0-9-\\+” , optional follow by “.[_A-Za-z0-9-]”, and end with a “@” symbol. The email’s domain name must start with “A-Za-z0-9-“, follow by first level Tld (.com, .net) “.[A-Za-z0-9]” and optional follow by a second level Tld (.com.au, .com.my) “\\.[A-Za-z]{2,}”, where second level Tld must start with a dot “.” and length must equal or more than 2 characters.

1. Java Regular Expression Example

Here’s a Java example to show you how to use regex to validate email address.

EmailValidator.java

package com.mkyong.regex;

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

public class EmailValidator {

	private Pattern pattern;
	private Matcher matcher;

	private static final String EMAIL_PATTERN = 
		"^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
		+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

	public EmailValidator() {
		pattern = Pattern.compile(EMAIL_PATTERN);
	}

	/**
	 * Validate hex with regular expression
	 * 
	 * @param hex
	 *            hex for validation
	 * @return true valid hex, false invalid hex
	 */
	public boolean validate(final String hex) {

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

	}
}

2. Valid Emails

1. mkyong@yahoo.com, mkyong-100@yahoo.com, mkyong.100@yahoo.com
2. mkyong111@mkyong.com, mkyong-100@mkyong.net, mkyong.100@mkyong.com.au
3. mkyong@1.com, mkyong@gmail.com.com
4. mkyong+100@gmail.com, mkyong-100@yahoo-test.com

3. Invalid Emails

1. mkyong – must contains “@” symbol
2. mkyong@.com.my – tld can not start with dot “.”
3. mkyong123@gmail.a – “.a” is not a valid tld, last tld must contains at least two characters
4. mkyong123@.com – tld can not start with dot “.”
5. mkyong123@.com.com – tld can not start with dot “.”
6. .mkyong@mkyong.com – email’s first character can not start with dot “.”
7. mkyong()*@gmail.com – email’s is only allow character, digit, underscore and dash
8. mkyong@%*.com – email’s tld is only allow character and digit
9. mkyong..2002@gmail.com – double dots “.” are not allow
10. mkyong.@gmail.com – email’s last character can not end with dot “.”
11. mkyong@mkyong@gmail.com – double “@” is not allow
12. mkyong@gmail.com.1a -email’s tld which has two characters can not contains digit

4. Unit Test

Here’s a unit test using testNG.

EmailValidatorTest.java

package com.mkyong.regex;

import org.testng.Assert;
import org.testng.annotations.*;

/**
 * Email validator Testing
 * 
 * @author mkyong
 * 
 */
public class EmailValidatorTest {

	private EmailValidator emailValidator;

	@BeforeClass
	public void initData() {
		emailValidator = new EmailValidator();
	}

	@DataProvider
	public Object[][] ValidEmailProvider() {
		return new Object[][] { { new String[] { "mkyong@yahoo.com",
			"mkyong-100@yahoo.com", "mkyong.100@yahoo.com",
			"mkyong111@mkyong.com", "mkyong-100@mkyong.net",
			"mkyong.100@mkyong.com.au", "mkyong@1.com",
			"mkyong@gmail.com.com", "mkyong+100@gmail.com",
			"mkyong-100@yahoo-test.com" } } };
	}

	@DataProvider
	public Object[][] InvalidEmailProvider() {
		return new Object[][] { { new String[] { "mkyong", "mkyong@.com.my",
			"mkyong123@gmail.a", "mkyong123@.com", "mkyong123@.com.com",
			".mkyong@mkyong.com", "mkyong()*@gmail.com", "mkyong@%*.com",
			"mkyong..2002@gmail.com", "mkyong.@gmail.com",
			"mkyong@mkyong@gmail.com", "mkyong@gmail.com.1a" } } };
	}

	@Test(dataProvider = "ValidEmailProvider")
	public void ValidEmailTest(String[] Email) {

		for (String temp : Email) {
			boolean valid = emailValidator.validate(temp);
			System.out.println("Email is valid : " + temp + " , " + valid);
			Assert.assertEquals(valid, true);
		}

	}

	@Test(dataProvider = "InvalidEmailProvider", dependsOnMethods = "ValidEmailTest")
	public void InValidEmailTest(String[] Email) {

		for (String temp : Email) {
			boolean valid = emailValidator.validate(temp);
			System.out.println("Email is valid : " + temp + " , " + valid);
			Assert.assertEquals(valid, false);
		}
	}
}

Here’s the unit test result.


Email is valid : mkyong@yahoo.com , true
Email is valid : mkyong-100@yahoo.com , true
Email is valid : mkyong.100@yahoo.com , true
Email is valid : mkyong111@mkyong.com , true
Email is valid : mkyong-100@mkyong.net , true
Email is valid : mkyong.100@mkyong.com.au , true
Email is valid : mkyong@1.com , true
Email is valid : mkyong@gmail.com.com , true
Email is valid : mkyong+100@gmail.com , true
Email is valid : mkyong-100@yahoo-test.com , true
Email is valid : mkyong , false
Email is valid : mkyong@.com.my , false
Email is valid : mkyong123@gmail.a , false
Email is valid : mkyong123@.com , false
Email is valid : mkyong123@.com.com , false
Email is valid : .mkyong@mkyong.com , false
Email is valid : mkyong()*@gmail.com , false
Email is valid : mkyong@%*.com , false
Email is valid : mkyong..2002@gmail.com , false
Email is valid : mkyong.@gmail.com , false
Email is valid : mkyong@mkyong@gmail.com , false
Email is valid : mkyong@gmail.com.1a , false
PASSED: ValidEmailTest([Ljava.lang.String;@15f48262)
PASSED: InValidEmailTest([Ljava.lang.String;@789934d4)

===============================================
    Default test
    Tests run: 2, Failures: 0, Skips: 0
===============================================

References

  1. http://en.wikipedia.org/wiki/E-mail_address
  2. http://tools.ietf.org/html/rfc2822#section-3.4.1

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
Nawaz
Guest
Nawaz

Hi am getting the below error, when i run your code..

please help.

[RemoteTestNG] detected TestNG version 6.11.0
org.testng.TestNGException:
com.bo.qa.testCases.EmailValidatorTest.invalidEmailTest() depends on nonexistent method ValidEmailTest
at org.testng.internal.MethodHelper.findDependedUponMethods(MethodHelper.java:112)
at org.testng.internal.MethodHelper.topologicalSort(MethodHelper.java:208)
at org.testng.internal.MethodHelper.sortMethods(MethodHelper.java:284)
at org.testng.internal.MethodHelper.collectAndOrderMethods(MethodHelper.java:57)
at org.testng.TestRunner.initMethods(TestRunner.java:472)
at org.testng.TestRunner.init(TestRunner.java:250)
at org.testng.TestRunner.init(TestRunner.java:220)
at org.testng.TestRunner.(TestRunner.java:169)
at org.testng.remote.support.RemoteTestNG6_10$1.newTestRunner(RemoteTestNG6_10.java:28)
at org.testng.remote.support.RemoteTestNG6_10$DelegatingTestRunnerFactory.newTestRunner(RemoteTestNG6_10.java:61)
at org.testng.SuiteRunner$ProxyTestRunnerFactory.newTestRunner(SuiteRunner.java:616)
at org.testng.SuiteRunner.init(SuiteRunner.java:185)
at org.testng.SuiteRunner.(SuiteRunner.java:131)
at org.testng.TestNG.createSuiteRunner(TestNG.java:1383)
at org.testng.TestNG.createSuiteRunners(TestNG.java:1363)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1217)
at org.testng.TestNG.runSuites(TestNG.java:1144)
at org.testng.TestNG.run(TestNG.java:1115)
at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:114)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)

LKr
Guest
LKr

What about the “Internationalization” chapter from https://en.wikipedia.org/wiki/Email_address ? From my point of view your pattern will not work with non US-ASCII adresses, right ?

Douglas De Rizzo Meneghetti
Guest
Douglas De Rizzo Meneghetti

I tried this code with “email@goes_here.com” and it was deemed invalid. I guess it’s because of the underscore.

Leonardo Cardozo Cadavid
Guest
Leonardo Cardozo Cadavid

blahblah#3@gmail.com is a valid email and this program is not working with that

Zhao Wu
Guest
Zhao Wu

org.apache.commons.validator.routines.EmailValidator.isValid(String) use “^\s*?(.+)@(.+?)\s*$” is work

Zavael
Guest
Zavael

not working for example: mkyong-100@test.yahoo-test.com

to fix this I updated to this (one more dash): ^[_A-Za-z0-9-\+]+(\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)*(\.[A-Za-z]{2,})$

karan
Guest
karan

hi i want to validate cc and bcc using regex please help me

karan
Guest
karan

hi can i get the same validation for cc and bcc in mail???

Rishav Kumar
Guest
Rishav Kumar

hii ,i want to restrict the user to use –(double dash) in email ,
lke “rishav–kumar@example.com ” should not be acceptable.
can u help me please?

Rethwik
Guest
Rethwik

What about rah@fan@gmail.com.. Is it Valid?
I don’t think so..

Panneer Selvam
Guest
Panneer Selvam

it’s not valid…@ not come twise

Marlon
Guest
Marlon

I LOVE YOU MAN!!! you saved my life million times

ceram1
Guest
ceram1

Regex must be ^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:.[a-zA-Z0-9-]+)*$

It’s from
http://www.w3.org/TR/html-markup/datatypes.html#form.data.emailaddress

Marvin
Guest
Marvin

it’s wrong. “*$” at the end should be “+$”. Without this, “john@john” without a top level domain would be valid.

Josemaloco
Guest
Josemaloco

Whatever you are doing, using regex for this is a very bad idea. Just read a few comments and you ll see dozens of non working cases.

Just use a known validator from apache commons:

EmailValidator.getInstance().isValid(emailString)

And thats it.

Davy Jones
Guest
Davy Jones

There are use cases you might not want to include fucking library for just email validation as like on android which is written in java.

Shamnad PS
Guest
Shamnad PS

Thank You :)

Guest
Guest
Guest

Found a problem while trying this: Inputs like “a@bcd.mail.com” shouldn’t be valid.

SwagMeister5000
Guest
SwagMeister5000

Why isn’t this valid? My current email is in the same format. This is a valid email format.

just
Guest
just

nice…

thx a lot..

a sincere blessing from hong kong…

God bless you and the world… ^__^

Slawek L
Guest
Slawek L

In regex is error, email “mkyong-100@yahoo.com-test.com” is valid but your code says false.
The regex should looks like:
“^[_A-Za-z0-9-\+]+(\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\.[A-Za-z0-9]+)*(\-[A-Za-z0-9]+)*(\.[A-Za-z]{2,})$”

Brian
Guest
Brian

Thank you for publishing this. It was of enormous help to me. I had to make some minor adjustments to make it work under Oracle. I hope this is of help:

‘^[_A-Za-z0-9+-]+(.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(.[A-Za-z0-9]+)*(.[A-Za-z]{2,})$’

Alex
Guest
Alex

Thank you! Helped a lot =)

Siebel
Guest
Siebel

Thanks Dude

Guest
Guest
Guest

ty my class is a shit for u :/

trackback
Email domain validation in java on server side « Jai’s Weblog – Tech, Security & Fun…

[…] How To Validate Email Address With Regular Expression to find the matching regular expression for Email […]

Binh Thanh Nguyen
Guest
Binh Thanh Nguyen

Thanks, nice post.

hi-tech
Guest
hi-tech

nice dude

Ashwani
Guest
Ashwani

adnamariqq@gmail is not a valid email but your regex is saying differently. It has passed your regex. How so?

Frank
Guest
Frank

this is not true, i typed that exact email in and it did not pass.

Adrian
Guest
Adrian

Thank You! Your regex is very valuable!

Matt
Guest
Matt

This email address is valid, but using the regex from this article, it says that it is not valid: test@ville.sainte-julie.qc.ca

free shop plans
Guest
free shop plans

Hey there! I could have sworn I’ve been to this website before but after reading through some of the post I realized it’s new to me.
Anyhow, I’m definitely happy I found it and I’ll
be bookmarking and checking back often!

Anonymous
Guest
Anonymous

var filter =/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
return (!filter.test(value)) ? false : true;

or

var filter = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
return (!filter.test(value)) ? false : true;

my choice

Arnau Aregall
Guest
Arnau Aregall

Try removing the wrapping slashes from the pattern and pass it to the RegExp constructor function as it follows :

var filter = new RegExp('^s*[w-+_]+(.[w-+_]+)*@[w-+_]+.[w-+_]+(.[w-+_]+)*s*$');
return(filter.test(value));

pradip garala
Guest
pradip garala

Perfect regex for email validation.

trackback
Email Validation | Blog Torsten Brieskorn