Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression for SSN [duplicate]

Tags:

c#

regex

I have a method in C# that says FormatSSN that takes a SSN in a string format and replaces the dashes. I mean I am expecting the SSN to be in XXX-XX-XXXX format. I want to write a regular expression that makes sure that the SSN is in the format I have mentioned.

Can anyone help me construct a regular expression??

like image 610
SaiBand Avatar asked Aug 15 '11 16:08

SaiBand


3 Answers

I used the simple expression in the past, but since there are some rules in the formation of SSN, I came up with something a little bit more elaborated:

^(?!000)(?!666)(?!9[0-9][0-9])\d{3}[- ]?(?!00)\d{2}[- ]?(?!0000)\d{4}$

This regex correctly excludes SSNs beginning with 666, 000 and 900-999, according to the Social Security Number Randomization.

You can try it out at Rubular.

like image 173
Tona Avatar answered Oct 19 '22 23:10

Tona


^\d{3}-\d{2}-\d{4}$

\d is a digit, {X} is repeat the previous element X times.

As Dmitry pointed out in comments, adding ^ at the beginning and $ at the end will cause the regex to only match if the entire string is a SSN. Without those anchors strings like abc123-45-6789xyz would also match.

like image 22
Andrew Clark Avatar answered Oct 19 '22 22:10

Andrew Clark


You can also try

[RegularExpression(@"^\d{9}|\d{3}-\d{2}-\d{4}$", 
ErrorMessage = "Invalid Social Security Number")]
like image 3
Bogdan Mates Avatar answered Oct 19 '22 23:10

Bogdan Mates