How to validate email, SSN, phone number in Java using Regular expressions.
Jan 10
Java, Most Popular Posts Java, Phone number, RegEx, Regular Expression, SSN, utility, Validate email 46 Comments
Regular Expressions offer a concise and powerful search-and-replace mechanism.
They are patterns of characters used to perform search, extract or replace operations on the given text. Regular expressions can also be used to validate that the input conforms to a given format.
For example, we can use Regular Expression to check whether the user input is a valid Social Security number, a valid phone number or a valid email number, etc.
Regular Expressions are supported by many languages. Sun added support for regular expression in Java 1.4 by introducing java.util.regex package. This package provides the necessary classes for using Regular Expressions in a java application. It consists of following three main classes ,
- Pattern
- Matcher
- PatternSyntaxException
The java.util.regex package has several other features for appending, text replacement, and greedy/non-greedy pattern matching. See the JDK Documentation on java.util.regex to learn more about using regular expressions in Java.
Using this package I created a utility class to validate some commonly used data elements. My FieldsValidation class has following methods:
1. isEmailValid:
Validate email address using Java regex
/** isEmailValid: Validate email address using Java reg ex.
* This method checks if the input string is a valid email address.
* @param email String. Email address to validate
* @return boolean: true if email address is valid, false otherwise.
*/
public static boolean isEmailValid(String email){
boolean isValid = false;
/*
Email format: A valid email address will have following format:
[\\w\\.-]+: Begins with word characters, (may include periods and hypens).
@: It must have a '@' symbol after initial characters.
([\\w\\-]+\\.)+: '@' must follow by more alphanumeric characters (may include hypens.).
This part must also have a "." to separate domain and subdomain names.
[A-Z]{2,4}$ : Must end with two to four alaphabets.
(This will allow domain names with 2, 3 and 4 characters e.g pa, com, net, wxyz)
Examples: Following email addresses will pass validation
[email protected]; [email protected]
*/
//Initialize reg ex for email.
String expression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
CharSequence inputStr = email;
//Make the comparison case-insensitive.
Pattern pattern = Pattern.compile(expression,Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputStr);
if(matcher.matches()){
isValid = true;
}
return isValid;
}
Update: Read this post for a more thorough Java regular expression to validate email address.
2. isPhoneNumberValid:
Validate phone number using Java reg ex.
/** isPhoneNumberValid: Validate phone number using Java reg ex.
* This method checks if the input string is a valid phone number.
* @param email String. Phone number to validate
* @return boolean: true if phone number is valid, false otherwise.
*/
public static boolean isPhoneNumberValid(String phoneNumber){
boolean isValid = false;
/* Phone Number formats: (nnn)nnn-nnnn; nnnnnnnnnn; nnn-nnn-nnnn
^\\(? : May start with an option "(" .
(\\d{3}): Followed by 3 digits.
\\)? : May have an optional ")"
[- ]? : May have an optional "-" after the first 3 digits or after optional ) character.
(\\d{3}) : Followed by 3 digits.
[- ]? : May have another optional "-" after numeric digits.
(\\d{4})$ : ends with four digits.
Examples: Matches following phone numbers:
(123)456-7890, 123-456-7890, 1234567890, (123)-456-7890
*/
//Initialize reg ex for phone number.
String expression = "^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{4})$";
CharSequence inputStr = phoneNumber;
Pattern pattern = Pattern.compile(expression);
Matcher matcher = pattern.matcher(inputStr);
if(matcher.matches()){
isValid = true;
}
return isValid;
}
3. isValidSSN:
Validate Social Security Number (SSN) using Java reg ex.
/** isSSNValid: Validate Social Security number (SSN) using Java reg ex.
* This method checks if the input string is a valid SSN.
* @param email String. Social Security number to validate
* @return boolean: true if social security number is valid, false otherwise.
*/
public static boolean isSSNValid(String ssn){
boolean isValid = false;
/*SSN format xxx-xx-xxxx, xxxxxxxxx, xxx-xxxxxx; xxxxx-xxxx:
^\\d{3}: Starts with three numeric digits.
[- ]?: Followed by an optional "-"
\\d{2}: Two numeric digits after the optional "-"
[- ]?: May contain an optional second "-" character.
\\d{4}: ends with four numeric digits.
Examples: 879-89-8989; 869878789 etc.
*/
//Initialize reg ex for SSN.
String expression = "^\\d{3}[- ]?\\d{2}[- ]?\\d{4}$";
CharSequence inputStr = ssn;
Pattern pattern = Pattern.compile(expression);
Matcher matcher = pattern.matcher(inputStr);
if(matcher.matches()){
isValid = true;
}
return isValid;
}
4. isNumeric:
Validate a number using Java regex.
/** isNumeric: Validate a number using Java regex.
* This method checks if the input string contains all numeric characters.
* @param email String. Number to validate
* @return boolean: true if the input is all numeric, false otherwise.
*/
public static boolean isNumeric(String number){
boolean isValid = false;
/*Number: A numeric value will have following format:
^[-+]?: Starts with an optional "+" or "-" sign.
[0-9]*: May have one or more digits.
\\.? : May contain an optional "." (decimal point) character.
[0-9]+$ : ends with numeric digit.
*/
//Initialize reg ex for numeric data.
String expression = "^[-+]?[0-9]*\\.?[0-9]+$";
CharSequence inputStr = number;
Pattern pattern = Pattern.compile(expression);
Matcher matcher = pattern.matcher(inputStr);
if(matcher.matches()){
isValid = true;
}
return isValid;
}
This example demonstrates how easy it is to validate email address, SSN, phone number in Java using regular expressions. You can read more about regular expression format here .
You can download complete Java code for this class here .
Feel free to modify and use this class in your projects. Let me know if you have any questions or comments.
Enjoy.
Related posts:
- Ultimate Java Regular Expression to validate any email address.
- How to validate date using Java regular expression
- How to validate Social Security Number (SSN) using JavaScript Regular Expressions
- Best way to check if a Java String is a number.
- Validate U.S Phone Numbers using JavaScript Regular expression.




Jan 23, 2008 @ 12:29:30
This explanation is very helpful. Very.
One minor question: It seems that the email validation accepts an underscore (“_”). I would have expected the validation to reject the character, because it is not specified in expression.
Jan 24, 2008 @ 14:41:51
Haro, the regular expression for email validation has a ‘\w’. \w stands for “word character” and that includes [A-Z], [a-z], [0-9] and the “underscore (_)” character. That is why if you have an “_” in your email address it will pass this validation.
Hope that clears it a bit.
Jan 27, 2008 @ 01:06:30
Really nice article
Apr 25, 2008 @ 10:26:30
Very nice article…Thank you!
May 22, 2008 @ 09:11:16
Really helpful! Thanks..
Jun 12, 2008 @ 03:42:47
zparacha, I’m sure you’re aware this email validator code doesn’t cope with all aspects of the RFC. So should point out it is not definitive (but then what is?)
Was using similar logic until working with an NHS hospital trust in the UK who happily allow apostrophes in the user part of the address (before @) e.g. kathy.o’[email protected]
After some argument needless to say the client won by waving his copy of the RFC around. Can’t imagine what problems these users have in general on the web when entering their email addresses, but I now use the simple .+@.+\\.[a-z]+ because I’m fed up with fighting.
As kajbj states at:
http://forum.java.sun.com/thread.jspa?threadID=5210483&messageID=9848968
“What about not performing validation at all? (I’m serious) Why do people validate email addresses? Either send a verification mail to the address or live with the fact that people will enter addresses that might be valid according to the RFC but don’t work.”
Mar 11, 2009 @ 07:22:08
Really useful post…
Apr 27, 2009 @ 19:03:00
Yes, finally, a validation that works. Thank you for putting this together.
Jun 11, 2009 @ 02:24:38
nene NO 1…aakaleste annam pedatha
Dec 07, 2009 @ 04:14:26
Interesting and nice article………….. thanks for the post
Aug 16, 2010 @ 01:50:30
It’s really superb…….
Sep 23, 2010 @ 07:17:36
i want to ask,,
widget like as ball which stay on left your web is cool
when mouse appointed that to move…
whether a service provide that widget for add widget at my website?
Sep 29, 2010 @ 23:30:18
its really helpful……thanks a lot
Oct 06, 2010 @ 00:31:31
Thank u very much.
Oct 10, 2010 @ 22:29:36
package proj2;
import java.util.regex.*;
import java.io.*;
public class SecondStage {
public static void main(String[] aArgs) throws IOException {
FileWriter fValid= new FileWriter(“/home/webonise/valid.txt”);
FileWriter fInvalid= new FileWriter(“/home/webonise/invalid.txt”);
String strRe=new String(“^([a-z0-9._%+-])+@[a-z0-9.-]+\\.(?:[A-Z]{2}|com|org|net|edu|gov|mil|biz|vsnl|yahoo|gmail|info|mobi|name|aero|asia|jobs|museum)+$”);
Pattern p = Pattern.compile(strRe,Pattern.CASE_INSENSITIVE |
Pattern.UNICODE_CASE | Pattern.MULTILINE);
try {
BufferedReader in = new BufferedReader(new FileReader(“/home/webonise/users.csv”));
String str2=”;”;
String str1=”\”";
String str;
String[] x=new String[2];
while ((str = in.readLine()) != null)
{
String trial[];
trial= str.split(str2);
try
{
for(int i=0;i<trial.length;i++)
{
x[i]=trial[i].replaceAll(str1,"");
x[i]=x[i].replaceAll(" ","");
}
Matcher m = p.matcher(x[1]);
if(m.matches())
{
fValid.write(str+"\n");
}
else
{
fInvalid.write(str+"\n");
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
fValid.close();
fInvalid.close();
in.close();
} catch (IOException e) {
System.out.println("IO Exception : "+e);
}
}
}
I think this wld help shorter and easier code…..valid and email stored in two separate file from *.csv file
Nov 04, 2010 @ 09:15:45
really good article it helped me goood
Dec 07, 2010 @ 16:06:11
Googled for “java ssn validation” and clicked on the first result. And here you gave the solution and it worked like a charm. You saved a lot of time.
Thanks.
Dec 12, 2010 @ 13:17:01
I were searching for this tips. You have covered them nicely.
Dec 28, 2010 @ 13:54:09
Can this code be used to validate dates, minus signs and periods?
Jan 04, 2011 @ 03:43:31
This regular expression is very useful for us…. thanks
Jan 26, 2011 @ 04:20:55
Hi,
You should improve your phone number validation to allow international numbers, not just US ones, following RFC 3966, for example. Then it would be *really* useful… Cheers!
Feb 02, 2011 @ 21:59:20
can you help me out,to write java regex for converting given number into indian currency format.
example:-
12345.678 would be 12,345.678
12345678 would be 1,23,45,678
Feb 04, 2011 @ 08:51:12
Renew your rss feed please, I reading texts on blogs news via opera rss reader.
Feb 24, 2011 @ 02:10:36
thank you.
Mar 02, 2011 @ 12:19:20
very useful!!
thx
Apr 16, 2011 @ 04:19:55
good artical
thanks
Ravi
jevan sathi
Jun 09, 2011 @ 07:23:14
Thanks for adding this together – that is the great article for all of us with our heads buried inside the keyboard all time.
Jun 25, 2011 @ 07:55:51
Good use of regular expressions!
Sep 09, 2011 @ 01:19:52
i want to know the procedure for validate a phonenumber which containing all zeros in struts
Sep 28, 2011 @ 16:00:54
Rattling clean internet site, regards for this post.
Dec 22, 2011 @ 02:19:48
i am sending my resume please check this file
Jan 11, 2012 @ 09:37:08
Forgive me for asking what might be a really easy question (I am new to this type of thing)just wondering how you can allow an empty space on a surname. Apparently this can happen!!!!! for example John Mc Ginty (as opposed to John McGinty)
the code we have at the moment is
# FULLNAME
case $f==’fullname’:
if(!preg_match(‘/^([a-zA-Z]+[.-]?[a-zA-Z])+(\s[a-zA-Z]+[.-]?[a-zA-Z]+[-]?[a-zA-Z]+)*$/’,$value))
{
$errors[$input] = “a valid $input”;
}
break;
Currently though it does seem to allow a second name of a three word name if that second name is at least 3 characters long. It wont allow it if is only 2 characters
i.e. John Mac Ginty allowed
but John Mc Ginty not allowed
Any ideas would be greatly appreciated!!!
Feb 16, 2012 @ 04:37:32
May sound stupid but … how do I call the routine isEmailValid after someone entered the e-mail address in an input field? I’d rather alert a message instead of returning true or false.
Feb 20, 2012 @ 17:33:23
This is NOT a legal phone number: 500-000-0000
Feb 20, 2012 @ 18:08:26
Can you *PLEASE* write normal, formatted code:
(function(){try{var s,a,i,j,r,c,l=document.getElementById(“__cf_email__”);a=l.className;if(a){s=”;r=parseInt(a.substr(0,2),16);for(j=2;a.length-j;j+=2){c=parseInt(a.substr(j,2),16)^r;s+=String.fromCharCode(c);}s=document.createTextNode(s);l.parentNode.replaceChild(s,l);}}catch(e){}})();
Mar 19, 2012 @ 22:21:12
Hope fully you will find the email validation from here
How to validate email address in Java Pattern
May 07, 2012 @ 22:49:59
ththr
May 09, 2012 @ 01:05:22
Hi to all,
I have one requirement
A four letter number(1234) doesn,t contains the 2nd and 3rd letter should not be equal.
VALID – 1234 , 1343,5656
INVALID – 1223,4556,5556
please let me know if any one know the regular expression for above requirement.
Thank You
May 10, 2012 @ 17:43:02
Googled for “java ssn validation” and clicked on the first result. And here you gave the solution and it worked like a charm. You saved a lot of time
thanks
May 10, 2012 @ 17:45:05
Googled for “java ssn validation” and clicked on the first result. And here you gave the solution and it worked like a charm. You saved a lot of time