How to validate email, SSN, phone number in Java using Regular expressions.
Regular Expressions offer a concise and powerful search-and-replace mechanism.
They are patterns of characters used to perform a 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 alphabets. (This will allow domain names with 2, 3 and 4 characters e.g pa, com, net, wxyz) Examples: Following email addresses will pass validation abc@xyz.net; ab.c@tx.gov */ //Initialize regex 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 an email address.
2. isPhoneNumberValid:
Validate phone number using Java regex.
/** 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 regex.
/** 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 regex 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 regex 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 an email address, SSN, phone number in Java using regular expressions. You can read more about regular expression format here.
Feel free to modify and use this class in your projects. Let me know if you have any questions or comments.
Enjoy.
haro
January 23, 2008 @ 12:29 pm
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.
GDD
January 27, 2008 @ 1:06 am
Really nice article
Linoleum
January 31, 2008 @ 2:43 am
Regular expressions in Java…
Confused by regular expressions in Java? This brief tutorial by zparacha may help shed some light on them……
Validate email address using JavaScript regular expression
February 7, 2008 @ 11:00 pm
[…] month I wrote about regular expressions in Java, today I’ll show you how to use regular expression in JavaScript to validate email […]
Java R
April 25, 2008 @ 10:26 am
Very nice article…Thank you!
Su
May 22, 2008 @ 9:11 am
Really helpful! Thanks..
A2D
June 12, 2008 @ 3:42 am
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’malley@xxx.nhs.uk
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.”
(Ultimate) Java Regular Expression to validate (any) email address. | zParacha.com
February 1, 2009 @ 3:55 pm
[…] post about Java regular expression gets a lot of hits daily. Someone commented that the regular […]
sivaraja
March 11, 2009 @ 7:22 am
Really useful post…
Brian Nettles
April 27, 2009 @ 7:03 pm
Yes, finally, a validation that works. Thank you for putting this together.
dasfasf
June 11, 2009 @ 2:24 am
nene NO 1…aakaleste annam pedatha
tiensstore
December 7, 2009 @ 4:14 am
Interesting and nice article………….. thanks for the post
selva
August 16, 2010 @ 1:50 am
It’s really superb…….
Fauzi
September 23, 2010 @ 7:17 am
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?
kuni biswal
September 29, 2010 @ 11:30 pm
its really helpful……thanks a lot
Santhosh Kumar
October 6, 2010 @ 12:31 am
Thank u very much.
Brijesh Kumar(WeboniseLab)
October 10, 2010 @ 10:29 pm
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
Adugna
November 4, 2010 @ 9:15 am
really good article it helped me goood
ocpjp
December 7, 2010 @ 4:06 pm
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.
autoresponder
December 12, 2010 @ 1:17 pm
I were searching for this tips. You have covered them nicely.
Pam Sheffey
December 28, 2010 @ 1:54 pm
Can this code be used to validate dates, minus signs and periods?
Narthanaraja
January 4, 2011 @ 3:43 am
This regular expression is very useful for us…. thanks
Jax1961
January 26, 2011 @ 4:20 am
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!
hemang
February 2, 2011 @ 9:59 pm
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
Patch Leilani
February 4, 2011 @ 8:51 am
Renew your rss feed please, I reading texts on blogs news via opera rss reader.
How to validate date using Java regular expression
February 13, 2011 @ 9:34 pm
[…] earlier post on how to validate email address, SSN and phone number validation using Java regex still attracts lot of visitors. Today I realized that another piece of […]
joy
February 24, 2011 @ 2:10 am
thank you.
Toni
March 2, 2011 @ 12:19 pm
very useful!!
thx
priya ranjan kumar
April 16, 2011 @ 4:19 am
good artical
thanks
Ravi
jevan sathi
Orson Holloway
June 9, 2011 @ 7:23 am
Thanks for adding this together – that is the great article for all of us with our heads buried inside the keyboard all time.
Java Coder
June 25, 2011 @ 7:55 am
Good use of regular expressions!
JavaPins
September 5, 2011 @ 8:10 am
How to validate email, SSN, phone number in Java using Regular expressions….
Thank you for submitting this cool story – Trackback from JavaPins…
Sujatha
September 9, 2011 @ 1:19 am
i want to know the procedure for validate a phonenumber which containing all zeros in struts
Dale Beaston
September 28, 2011 @ 4:00 pm
Rattling clean internet site, regards for this post.
javed khan
December 22, 2011 @ 2:19 am
i am sending my resume please check this file
Dan J
January 11, 2012 @ 9:37 am
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!!! 🙂
beste-els
February 16, 2012 @ 4:37 am
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.
Helen
February 20, 2012 @ 5:33 pm
This is NOT a legal phone number: 500-000-0000
Bonnie
February 20, 2012 @ 6:08 pm
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){}})();
JSupport
March 19, 2012 @ 10:21 pm
Hope fully you will find the email validation from here
How to validate email address in Java Pattern
rrgrgrtrhr
May 7, 2012 @ 10:49 pm
ththr
venkat
May 9, 2012 @ 1:05 am
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
subbu
May 10, 2012 @ 5:43 pm
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
High PR Expired Domains
May 10, 2012 @ 5:45 pm
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
cheap diablo 3 gold
June 14, 2012 @ 11:14 pm
Wonderful site. A lot of useful information here. I?m sending it to some pals ans also sharing in delicious. And of course, thank you for your effort!
where find cheap cheapest Diablo 3 Gold
June 19, 2012 @ 9:12 am
My wife and i were very thrilled when Raymond managed to round up his web research with the precious recommendations he was given while using the weblog. It is now and again perplexing to simply possibly be releasing tricks which usually the rest might have been trying to sell. We really understand we now have you to thank for this. Those illustrations you made, the straightforward website navigation, the relationships your site make it possible to promote – it is mostly wonderful, and it is making our son in addition to us understand this topic is thrilling, which is certainly wonderfully vital. Thanks for the whole thing!
Daidaihua
March 14, 2013 @ 9:28 am
Happy to have discover it. Plus I have voiced to so several persons about my outcome of losing 20 pounds. I choose 1 tablet every morning and choose a person at lunch for a double dose, and that i keep getting better results. I also have more energy and even sleep more soundly, which helps me to make better food choices, ditch the fatty mochas in the morning, and sense great all day. This is a great product or service. Daidaihua http://www.slimmingcapsulesbuy.com/original-lida-pills-p-6.html
Marshall Volkers
May 3, 2013 @ 4:46 am
Speaking of the top level domain name since this plays a large role in picking the right domain name for domain name registration; many experts have noted that before you go for a domain name registration, you should identify your top level domain. The .com is the most common top level domain that is used today, for it stands for commercial domains. Of course there are other types and each has its own uses and functions.`*
Brand new posting on our very own blog
<http://healthmedicinelab.com/
website
June 30, 2013 @ 1:12 am
Furthermore, it is also recommended that you ask family and associates for a good plumbing service
or company. ” flooded homes, clogged bathrooms, overflowing kitchen sinks and even toilet bowls that flush the wrong side. Regular maintenance and prompt HVAC repair will keep your system working efficiently for long and consequently it would help you reduce your energy bills.
Ellie
July 26, 2013 @ 8:47 pm
Thankfulness to my father who told me on the topic of this web site, this website is actually awesome.
LYNN
October 18, 2013 @ 11:44 pm
My spouse and I stumbled over here coming from a different website and thought I may as well check things out. I like what I see so now i am following you. Look forward to finding out about your web page repeatedly.
christian louboutin pas cher
February 19, 2014 @ 10:36 am
http://www.brunifarmacia.it/it/hogan-italy.aspscarpe hogan
tn requin pas cher
February 19, 2014 @ 1:17 pm
“Il y a des investigations en Allemagne pour retrouver Claudia, (une ancienne maitresse de XDDL, ndlr), de nouvelles fouilles sont prévues dans le sud-est de la France”, ajoute la procureure.
tn requin pas cher http://www.tataproductions.com/fr/NikeTnRequinPasCher.php
Linda
July 4, 2014 @ 8:54 am
This post is very interesting but it took me a long time to find it in google.
I found it on 20 spot, you should focus on quality backlinks building, it will
help you to rank to google top 10. And i know how to help you, just search in google –
k2 seo tips
Sinoo
September 12, 2014 @ 12:31 am
hi all, thanks for the expressions..
I’m working on the ssn validation, my code needs to autofill the dashes in the ssn if user just captures numbers. can anyone please assist?
Santhosh
April 17, 2015 @ 6:33 am
Thanks for ur info…..
Sushil
October 20, 2016 @ 5:52 am
thnx a lot for ur help .!!!
Rainbowdo32i
February 12, 2017 @ 4:55 pm
http://newitech.pl/inwestycje-w-drogi
Buying a used or new automobile can be quite a difficult approach if you do not know what you are actually performing. By teaching yourself about car purchasing prior to head to the dealer, you possibly can make stuff simpler yourself. The following advice may help the next shopping getaway be more pleasurable.
Generally bring a auto technician alongside when searching for a new vehicle. Auto dealers are popular for offering lemons and you do not desire to be their after that target. Provided you can not get a auto mechanic to think about autos together with you, a minimum of make certain you have him take a look at last choice before you buy it.
Know your limits. Before you start purchasing for your upcoming vehicle or truck, determine what you can afford to pay out, and adhere to it. Don’t overlook to incorporate curiosity about your computations. You can expect to pay all around twenty percent as a down payment at the same time, so be ready.
Well before visiting a dealership, know what kind of motor vehicle you need. Study each one of you alternatives ahead of buying so that you can figure out what works well with your financial budget and household needs. Do your homework to determine exactly how much you must pay to get a prospective car.
Prior to signing any agreement take the time to go through each and every collection, including the small print. If there is anything listed that you just do not recognize, do not indicator before you get an solution that you simply fully grasp. Unsavory salesmen may use a contract to put in several service fees that have been not discussed.
When you maintain the preceding guidance under consideration when that you just go buying a vehicle, you will end up prone to get a good offer. Getting a auto lacks as a frustration. Use the ideas from this report and you can have the car you need at a very good price.
mcdonalds
August 21, 2017 @ 7:02 am
We arre a group oof volunteers andd opening a brand new scheme in our community.
Yoour website offered us with useful info to woek on. You’ve done a formidable task annd our
whole ggroup wil likely be thankful to you.