How to validate email, SSN, phone number in Java using Regular expressions.


Email
Email

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
abc@xyz.net; ab.c@tx.gov
*/

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

crystaljingsr

Comments 61

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

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

  • Really nice article

  • Regular expressions in Java…

    Confused by regular expressions in Java? This brief tutorial by zparacha may help shed some light on them……

  • How To essentials – Regular expressions in Java | Deliggit.com…

    zparacha.com

    How to validate email, SSN, phone number in Java using Regular expressions.

    This…

  • […] month I wrote about regular expressions in Java, today I’ll show you how to use regular expression in JavaScript to validate email […]

  • Very nice article…Thank you!

  • Really helpful! Thanks..

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

  • […] post about Java regular expression gets a lot of hits daily. Someone commented that the regular […]

  • Really useful post…

  • Yes, finally, a validation that works. Thank you for putting this together.

  • nene NO 1…aakaleste annam pedatha

  • Interesting and nice article………….. thanks for the post

  • It’s really superb…….

  • 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?

  • its really helpful……thanks a lot

  • Thank u very much.

  • 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

  • really good article it helped me goood

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

  • I were searching for this tips. You have covered them nicely.

  • Can this code be used to validate dates, minus signs and periods?

  • This regular expression is very useful for us…. thanks

  • 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!

  • 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

  • Renew your rss feed please, I reading texts on blogs news via opera rss reader.

  • […] 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 […]

  • very useful!!

    thx

  • good artical

    thanks
    Ravi
    jevan sathi

  • Thanks for adding this together – that is the great article for all of us with our heads buried inside the keyboard all time.

  • Good use of regular expressions!

  • How to validate email, SSN, phone number in Java using Regular expressions….

    Thank you for submitting this cool story – Trackback from JavaPins…

  • i want to know the procedure for validate a phonenumber which containing all zeros in struts

  • Rattling clean internet site, regards for this post.

  • i am sending my resume please check this file

  • 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!!! 🙂

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

  • This is NOT a legal phone number: 500-000-0000

  • 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){}})();

  • Hope fully you will find the email validation from here

    How to validate email address in Java Pattern

  • 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

  • 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

  • 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

  • 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!

  • 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!

  • 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

  • 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/

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

  • Thankfulness to my father who told me on the topic of this web site, this website is actually awesome.

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

  • “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

  • 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

  • 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?

  • Thanks for ur info…..

  • thnx a lot for ur help .!!!

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

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

Leave a Reply

Your email address will not be published. Required fields are marked *