Saturday, January 5, 2013

How to validate a Social Security Number(SSN) using Java.

How to validate a SSN Number using Java?

SSNValidator class.

import java.util.regex.*;
class SSNValidator{
     public static void isValidSSN(String ssn) throws Exception{
 
        //Initialize reg expression 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()){
            System.out.println("Correct SNN Number");
            }
            else{
                throw new MyException(ssn);
            }           
    }
    public static void main(String args[])throws Exception{   
                String cmd="";
                try{
                     cmd=args[0];
                    }
                    catch(ArrayIndexOutOfBoundsException ae){
                    System.out.println("You shoud input your SSN number");
                    }
                isValidSSN(cmd);               
    }
}

Creating my own Exception class by extending Exception class.
class MyException extends Exception{
    private String s="";
    MyException(String val){
        this.s=val;
   
    }
      public String toString(){
        return "SSN number you were enter" + " " +s+" is not valid. "+ "please try again with correct format as given here. Ex:123-44-5678";
    }
}
  
How to run?
  1. Copy both java sources into one folder.
  2. Open cmd and navigate to that folder.
  3. Compile  main class(SSNValidator). 
  4. Then run with the SSN number. Ex(java SSNValidator 123-67-7890).
Meaning of Regex expression:
        "^\\d{3}[- ]\\d{2}[- ]\\d{4}$";
        ^\\d{3}:  Starts with three numeric digits.
        [- ]:  Followed by an "-"
        \\d{2}: Two numeric digits after the "-"
        [- ]:  contain an second "-" character.
       \\d{4}: ends with four numeric digits.
Above Regex format accepts only following format "xxx-xx-xxxx".
If you would like to change the Regex expression to accept 9 digits regardless of above format.
String expression = "^\\d{3}[- ]?\\d{2}[- ]?\\d{4}$"; 
This expression can accept the format given below.
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.


No comments:

Post a Comment