IsoCodes\Ssn::validate PHP Method

validate() public static method

Validate a SSN.
public static validate ( mixed $ssn ) : boolean
$ssn mixed
return boolean : false, or two letter state abbreviation if it is valid
    public static function validate($ssn)
    {
        if (!static::$initialized) {
            static::initialize();
            static::$initialized = true;
        }
        if (!is_string($ssn)) {
            return false;
        }
        if (trim($ssn) === '') {
            return false;
        }
        $statePrefixes = static::$statePrefixes;
        $highgroup = static::$highgroup;
        $possibleGroups = static::$possibleGroups;
        // Split up the SSN
        // If not 9 or 11 long, then return false
        $length = strlen($ssn);
        if ($length == 9) {
            $areaNumber = substr($ssn, 0, 3);
            $groupNumber = substr($ssn, 3, 2);
            $lastFour = substr($ssn, 5);
        } elseif ($length == 11) {
            $areaNumber = substr($ssn, 0, 3);
            $groupNumber = substr($ssn, 4, 2);
            $lastFour = substr($ssn, 7);
        } else {
            return false;
        }
        // Strip leading zeros
        $areaNumber = ltrim($areaNumber, 0);
        $groupNumber = ltrim($groupNumber, 0);
        // Check if parts are numeric
        if (!is_numeric($areaNumber) || !is_numeric($groupNumber) || !is_numeric($lastFour)) {
            return false;
        }
        foreach ($statePrefixes as $numbers) {
            // Search for the area number in the state list
            if (in_array($areaNumber, $numbers)) {
                // Make sure the group number is valid
                if (array_search($highgroup[$areaNumber], $possibleGroups) >= array_search($groupNumber, $possibleGroups)) {
                    //return $state => must use "as $state => numbers" in the foreach loop;
                    return true;
                } else {
                    return false;
                }
            }
        }
        return false;
    }

Usage Example

Example #1
0
 /**
  * testInvalidSsn
  *
  * @param mixed $ssn
  *
  * @dataProvider getInvalidSsn
  *
  * return void
  */
 public function testInvalidSsn($ssn)
 {
     $this->assertFalse(Ssn::validate($ssn));
 }