Skip to content

Instantly share code, notes, and snippets.

@algonzalez
Created August 21, 2023 20:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save algonzalez/4edb2ebaa2c4d6314269ac26a458e608 to your computer and use it in GitHub Desktop.
Save algonzalez/4edb2ebaa2c4d6314269ac26a458e608 to your computer and use it in GitHub Desktop.
SSN Validation Regex
public class RegexPatterns
{
/// <summary>
/// Regular expression used to validate an US Social Security Number (SSN)
/// formatted as nine-digits with hyphens (###-##-####).
/// </summary>
/// <example>
/// <code>
/// var ssnRegex = new Regex(RegexPatterns.Ssn);
/// ssnRegex.IsMatch("078-05-1120"); // should return false
/// </code>
/// </example>
// TODO: should other consecutive numbers fail (ex. 234-56-7890)?
public static readonly string Ssn
// cannot be: 078-05-1120 (Woolworth advertising - https://www.ssa.gov/history/ssn/misused.html),
// 123-45-6789 (sequential digits),
// 219-09-9999 (SSA advertising from 1940),
// 457-55-5462 (LifeLock CEO's SSN),
// nor 721-07-4426 (1943 deceased and shown in Wikipedia)
= "(?!078-05-1120|123-45-6789|219-09-9999|457-55-5462|721-07-4426)"
// cannot be all the same digit (e.g. 555-55-5555)
+ @"(?!\b([0-9])\1+-([0-9])\1+-([0-9])\1+\b)"
+ "(?!000|666|9)" // cannot start with 000, 666 or 900-999
+ "[0-9]{3}-" // must start with 3 digits followed by a dash
+ "(?!00)" // cannot be 00
+ "[0-9]{2}-" // must be 2 digits followed by a dash
+ "(?!0{4})" // cannot be 0000
+ "[0-9]{4}"; // end end string
/// <summary>
/// Regular expression used to validate an US Social Security Number (SSN)
/// formatted as nine-digits with no hyphens (#########).
/// </summary>
public static readonly string SsnWithNoDashes
= Ssn.Replace("-", "").Replace("[09]", "[0-9]");
/// <summary>
/// Regular expression used to validate an US Social Security Number (SSN)
/// formatted as nine-digits with "optional" hyphens (#########, ###-######, #####-#### or ###-##-####).
/// </summary>
public static readonly string SsnWithOptionalDashes
= Ssn.Replace("-", "-?").Replace("[0-?9]", "[0-9]");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment