I think this is a good example where a longer solution might be worth considering. I believe it’s much more important to get code readable and understandable, simply reading the code should tell you what it does. And you have to either spend some time with those regexes - or be a bit too comfortable with regexes in order to see what’s actually going on.
[php]/**
-
@param string $string
-
@return bool
*/
function validateSocialSecurityNumberFormat($string)
{
if(strlen($string) !== 10) return false;
list($date, $number) = str_split($string, 6);
$d = DateTime::createFromFormat(‘dmy’, $date);
return $d && $d->format(‘dmy’) === $date && is_numeric($number);
}
var_dump(validateSocialSecurityNumberFormat(‘0305161234’));[/php]
Changed the function name to what I think this actually does. Since it doesn’t actually check if it is a valid social security number, I landed on validating the format.
Removed the line that made it valid if no string was submitted. If the application elsewhere doesn’t care if it’s valid if it’s not submitted, then do that check outside this function.
Changed the code to split the string and do more readable (??) checks on the format.