SSN Regex Python Validator

Search...

⌘K

SSN Regex Python Validator

Search...

⌘K


SSN Regex Python Validator

Validate US Social Security Numbers (SSNs) effortlessly with the SSN Regex Python Validator. This tool ensures the correct “AAA-GG-SSSS” structure using Python’s re module. Also explore Email Regex Python Validator, Phone Number Regex Python Validator, and Python Regex Tester for broader input validation.

123-45-6789
Possible security issues
This regex appears to be safe.
Explanation
  • [A-Z]: uppercase letters
  • [a-z]: lowercase letters
  • [0-9]: digits
  • \.: a literal dot
  • +: one or more of the preceding
  • *: zero or more of the preceding
  • ?: optional (zero or one)
  • ^: start of string
  • $: end of string
Test your APIs today!

Write in plain English — Qodex turns it into secure, ready-to-run tests.

Regular Expression - Documentation

What is SSN Regex?


A Social Security Number (SSN) in the U.S. follows the standard format:

XXX-XX-XXXX


where:

  • XXX: Area number (3 digits)

  • XX: Group number (2 digits)

  • XXXX: Serial number (4 digits)


This format ensures structured identification for tax and legal purposes. Using regex helps validate whether an input string follows this format strictly.

To be considered a valid SSN, a string must also meet these specific criteria:

  • 9 digits total, separated into three parts by hyphens ().

  • First part (Area Number): 3 digits; cannot be , , or any value between and .

  • Second part (Group Number): 2 digits; must range from to (not ).

  • Third part (Serial Number): 4 digits; must range from to (not ).

These rules help ensure that only properly structured and potentially valid SSNs pass validation, reducing errors and improving data integrity.


SSN Regex Pattern


The typical regex pattern to validate a properly formatted SSN is:

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


Breakdown:

  • ^\d{3} → Three digits at the start

  • - → First hyphen separator

  • \d{2} → Two digits

  • - → Second hyphen

  • \d{4}$ → Four digits at the end


This ensures strict format matching like 123-45-6789.


Expanded Patterns and Considerations


While the above pattern covers the standard SSN format, there are a few additional scenarios and stricter checks you might consider:

  • Strict Invalid Value Exclusions:
    To avoid obviously invalid SSNs, you can use a more restrictive regex that excludes certain values:

    ^(?!(0006669))\d{3}-(?!00)\d{2}-(?!0000)\d{4}$

    • This pattern prevents area numbers of , , or any number starting with , as well as group numbers of and serial numbers of , which are not valid per official guidelines.

  • Masked or Placeholder SSNs:
    Sometimes, placeholders like are used in documentation or forms. To account for these, you can allow either a valid SSN or the placeholder:

    ^(\d{3}-\d{2}-\d{4}XXX-XX-XXXX)$

    • This matches either a real SSN or the common masked format.

  • Flexible Formatting:
    If you want to allow optional hyphens or even support lowercase or uppercase placeholders (e.g., ), consider:

    ^(\d{3}-?\d{2}-?\d{4}[Xx]{3}-?[Xx]{2}-?[Xx]{4})$

    • This pattern supports both standard and masked forms, with or without hyphens, and accepts both uppercase and lowercase 'x'.

Choose the pattern that best fits your use case—whether you need strict validation for official data entry or more lenient matching for placeholder or sample values.


What Makes an SSN Valid?


It’s not just about the pattern—there are rules beneath the surface:

  • Nine digits total: The SSN must contain exactly nine digits, split by hyphens.

  • Three parts by hyphens: The format is always .

  • Area number restrictions: The first three digits (the area number) should not be , , or any number from to .

  • Group number restrictions: The middle two digits (the group number) must be between and — is not valid.

  • Serial number restrictions: The last four digits (the serial number) should range from to — is not valid.

So, while a regex like checks the format, true SSN validation involves additional logic to ensure the number itself falls within these official boundaries. This helps catch invalid entries such as , , or , which, while matching the basic pattern, are not legitimate SSNs.

By combining regex with these additional checks, you can more confidently determine whether a given string is a valid SSN—not just a well-formatted one.


Python Example Code


import re

def is_valid_ssn(ssn):
    pattern = re.compile(r'^\d{3}-\d{2}-\d{4}$')
    return bool(pattern.fullmatch(ssn))

# Test Cases
print(is_valid_ssn("123-45-6789"))  # True
print(is_valid_ssn("123456789"))    # False
print(is_valid_ssn("12-345-6789"))  # False

Test regex variations with the Python Regex Tester.


Time and Space Complexity


Validating an SSN using a regular expression in Python is highly efficient:

  • Time Complexity: Checking a string against the SSN regex runs in O(N) time, where N is the length of the SSN string. This is because the regex engine scans through each character once to verify the format.

  • Space Complexity: The regex validation uses O(1) auxiliary space since it doesn’t require storing additional data proportional to the input size—just a handful of pattern-matching variables behind the scenes.

In practice, this means SSN validation with regex is both fast and lightweight, making it suitable for everything from web form checks to large database sweeps.


Use Cases


  • User Identity Verification: Ensure accurate SSN input during user registration or onboarding.

  • Data Cleaning: Detect and correct improperly formatted SSNs in databases.

  • Security & Compliance: Verify SSN format before transmitting sensitive data.


You can combine this with:


Regex Metacharacters Used


  • ^ : Anchors the start of the string

  • \d : Matches any digit (0–9)

  • {n} : Matches exactly n digits

  • - : Matches literal hyphens in SSNs

  • $ : Anchors the end of the string


How to Validate SSNs in JavaScript


If you need to confirm US Social Security Numbers on the frontend (or in any JavaScript-powered environment), you can use a regular expression to ensure each input follows the “AAA-GG-SSSS” convention.

Here’s a simple approach using JavaScript’s built-in RegExp:

// Regular expression for strict SSN validation
const ssnPattern = /^(?!6660009\d{2})\d{3}-(?!00)\d{2}-(?!0{4})\d{4}$/;

function isValidSSN(ssn) {
  if (!ssn) return false; // Reject empty inputs
  return ssnPattern.test(ssn);
}

// Example usage:
console.log(isValidSSN("856-45-6789")); // true (valid)
console.log(isValidSSN("000-45-6789")); // false (invalid area)
console.log(isValidSSN("856-452-6789")); // false (incorrect format)
console.log(isValidSSN("856-45-0000")); // false (invalid serial)

What the Regex Does

  • Ensures the area number (first three digits) isn’t 666, 000, or within the 900–999 range.

  • Confirms the group number (middle two digits) isn't 00.

  • Verifies the serial number (last four digits) isn’t all zeros.

  • Forces proper hyphen placement.

This pattern guards against obvious fakes and badly formatted numbers. For more advanced needs, consider combining it with additional verification (such as querying official databases), but for format validation, this approach is solid.

Test JavaScript regexes using your favorite tool—or integrate the logic above into your web forms for real-time validation.


Java Example for SSN Validation


If you need to validate SSNs in a Java application, you can use the Pattern and Matcher classes from Java's standard library. Here’s a simple way to perform strict SSN validation using regex:

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class SSNValidator {
    // Regular expression for strict SSN validation
    private static final String SSN_REGEX =
        "^(?!6660009\\d{2})\\d{3}-(?!00)\\d{2}-(?!0{4})\\d{4}$";
    private static final Pattern pattern = Pattern.compile(SSN_REGEX);

    public static boolean isValidSSN(String ssn) {
        if (ssn == null) return false;
        Matcher matcher = pattern.matcher(ssn);
        return matcher.matches();
    }

    public static void main(String[] args) {
        // Example SSNs to test
        System.out.println(isValidSSN("856-45-6789"));   // true
        System.out.println(isValidSSN("000-45-6789"));   // false
        System.out.println(isValidSSN("856-452-6789"));  // false
        System.out.println(isValidSSN("856-45-0000"));   // false
    }
}

Explanation:

  • The regex ensures the SSN does not start with "666", "000", or a number beginning with "9".

  • Group (middle) must not be "00".

  • Serial (last group) must not be "0000".

  • All other digits must match the "XXX-XX-XXXX" structure.

This approach helps catch common invalid SSNs, and you can easily expand the logic for further checks as needed.


C# Example: Validating SSNs


If you’re working with .NET or building apps in C#, you can also harness regular expressions to validate Social Security Numbers. While the approach is similar to Python, C#’s Regex class offers precise control and flexibility.

Here’s a straightforward example of SSN validation logic in C#:

using System;
using System.Text.RegularExpressions;

public class SSNValidator
{
    // Validate US SSN format and value constraints
    public static bool IsValidSSN(string ssn)
    {
        // Regex:
        // - Area numbers (first three digits) can't be 000, 666, or 900-999
        // - Group (middle two digits) can't be 00
        // - Serial (last four digits) can't be 0000
        string pattern = @"^(?!6660009\d{2})\d{3}-(?!00)\d{2}-(?!0000)\d{4}$";
        return Regex.IsMatch(ssn, pattern);
    }

    public static void Main()
    {
        var testSSNs = new[]
        {
            "856-45-6789",   // Valid
            "000-45-6789",   // Invalid area
            "856-452-6789",  // Invalid format
            "856-45-0000"    // Invalid serial
        };

        foreach (var ssn in testSSNs)
        {
            Console.WriteLine($"{ssn}: {IsValidSSN(ssn)}"

How it works:

  • The regular expression checks both the numeric structure and disallows invalid area, group, and serial numbers.

  • The IsValidSSN method returns true for valid SSNs conforming to real-world rules—not just format.

  • Run this code in any C# environment (like Visual Studio, JetBrains Rider, or online C# editors) to validate your inputs.

This follows a similar logic to the Python example above, ensuring both format and validity constraints are enforced for US Social Security Numbers.


C++ Implementation for SSN Validation


Need to validate Social Security Numbers in C++? You can apply a similar pattern-matching technique using the <regex> library. Here’s how you can perform strict SSN format checks, guarding against common invalid entries:

#include 
#include 
#include 

bool is_valid_ssn(const std::string& ssn) {
    // Pattern enforces:
    // - Area number cannot be 000, 666, or in the 900–999 range
    // - Group number cannot be 00
    // - Serial number cannot be 0000
    std::regex pattern(R"(^(?!6660009\d{2})\d{3}-(?!00)\d{2}-(?!0000)\d{4}$)");
    return std::regex_match(ssn, pattern);
}

int main() {
    std::string samples[] = {
        "856-45-6789",  // Valid
        "000-45-6789",  // Invalid (Area)
        "856-452-6789", // Invalid (Group)
        "856-45-0000"   // Invalid (Serial)
    };

    for (const auto& ssn : samples) {
        std::cout << ssn << ": " << (is_valid_ssn(ssn) ? "Valid" : "Invalid") << std::endl;
    }
    return 0;
}

This approach closely mirrors the regex logic used in Python. The regular expression works to block out prohibited values for area, group, and serial numbers per official SSN assignment rules.

  • Area Number (first three digits): Must not be 000, 666, or within the 900–999 range.

  • Group Number (middle two digits): Must not be 00.

  • Serial Number (last four digits): Must not be 0000.

With this C++ snippet, you can quickly integrate SSN validation directly into your application logic.


Matching Only Numeric or Fully Masked SSNs — Not a Mix


Sometimes, you’ll want your SSN validation to accept either fully numeric (like 123-45-6789) or fully masked (like XXX-XX-XXXX) formats—but never a combination like 12X-4X-67X9. To achieve this with regex, the trick is to build a pattern that matches either format exclusively.

Here’s how you can approach it:

  • Pattern 1 (Standard): Three digits, dash, two digits, dash, four digits:
    ^\d{3}-\d{2}-\d{4}$

  • Pattern 2 (Masked): Three Xs, dash, two Xs, dash, four Xs:
    ^[Xx]{3}-[Xx]{2}-[Xx]{4}$

To allow either the standard or masked format but not mixtures, combine them with a logical “or” using the pipe (``):

^(\d{3}-\d{2}-\d{4}[Xx]{3}-[Xx]{2}-[Xx]

This regex ensures your input is all numbers or all Xs (with dashes in place) and won’t let through strings that blend the two. You can add the case-insensitive (i) flag to let lowercase x pass, too.


Matching Numeric and Masked SSNs with Regex


To validate both real numeric SSNs and their masked counterparts (using Xs), we can craft a regex that allows either format, but not a mixture of the two.

Here's a pattern that works:

This expression will match:

  • Standard numeric SSNs: 123-45-6789

  • Fully masked SSNs: XXX-XX-XXXX

Each block must be either all digits or all uppercase Xs, preserving the familiar AAA-GG-SSSS structure with required hyphens in between. If you want to accept lowercase X (e.g., xxx-xx-xxxx), simply add the re.IGNORECASE flag in Python or use the i modifier in many regex engines.

Note: This pattern enforces a strict match—only all digits or all Xs are allowed in each respective block, not a mix. Use this approach when you need to allow for placeholder masking (common in reporting or redacted datasets) in addition to valid numeric entries.


Allowing 'X' (Upper or Lower Case) in SSN Regex


Sometimes, you might encounter scenarios where the letter 'X' is used as a placeholder within the SSN format—common in test data or anonymized records. To support both uppercase 'X' and lowercase 'x' alongside digits, you can modify your regex pattern accordingly.

Enhanced Regex Pattern:

^[\dXx]{3}-[\dXx]{2}-[\dXx]

Explanation:

  • [\dXx]: Matches any digit, 'X', or 'x' in each component of the SSN.

  • The rest of the pattern preserves the strict hyphen-separated structure.

This adjustment makes your validator flexible enough for data masking or legacy systems that substitute 'X' or 'x' for unknown SSN digits.


Using Case-Insensitive Regex for SSNs with 'x' or 'X'


Sometimes, systems allow the use of 'x' or 'X' within SSNs to mask or anonymize numbers (like 123-xx-xxxx). If you want your regex to recognize both lowercase and uppercase 'x', you can add the case-insensitive (i) flag.

For example, a pattern like ^[\dX]{3}-?[\dX]{2}-?[\dX]{4}$ with the i flag will match both 'x' and 'X'. This means:

  • 123-45-6789 is valid,

  • 123-xx-xxxx is also valid,

  • And so is 123-XX-XXXX.

Trade-Offs and Considerations


  • Broader matching: With the i flag, you’re allowing both 'x' and 'X' as placeholders anywhere digits appear.

  • Data quality: Be mindful—this opens the door for mixed-case entries (123-xX-xXxX). If you only want to allow lowercase or uppercase 'x', skip the i flag and specify your preference directly in the pattern.

  • Use cases: Accepting mask characters like 'x' may be helpful for storing partially redacted SSNs, especially when importing data from legacy systems.

If you want to offer both strict and "masked" formats, you can combine patterns:

  • One pattern for fully numeric SSNs (^\d{3}-\d{2}-\d{4}$)

  • Another for masked forms (^x{3}-x{2}-x{4}$ with or without i for case flexibility)

Just be sure to clearly communicate to users and systems what input formats are allowed, and always sanitize or validate accordingly to maintain data integrity.


Using Regex Alternatives (``) for Multiple SSN Formats


Sometimes, Social Security Numbers might appear in more than one valid format—such as the classic “123-45-6789” or as a placeholder like “XXX-XX-XXXX.” If you want your validator to accept either format, regex alternatives come in handy. The pipe character `` acts as an “or”—it lets you specify more than one pattern within a single expression.

For example, to match either a numeric SSN or its anonymized counterpart, your regex might look like:

Here’s what happens:

  • \d{3}-\d{2}-\d{4} matches a typical numerical SSN.

  • XXX-XX-XXXX matches the common masked format.

  • Parentheses group each format, and the pipe `` tells regex to accept either pattern.

  • The anchors ^ and $ make sure the entire input strictly matches one pattern or the other.

You can even expand this idea to allow for variations, like accepting both uppercase and lowercase 'x' in masked SSNs. For that, adjust the pattern to something like:

^(\d{3}-\d{2}-\d{4}[Xx]{3}-[Xx]{2}-[Xx]

This flexibility makes the pipe operator a valuable tool whenever you want to match multiple legitimate ways an SSN might appear. Now, let’s see how you might use this in Python:


Pro Tips


  • Always anchor patterns with ^ and $ to avoid partial matches.

  • Preprocess user input to trim whitespaces before validation.

  • You can extend validation to exclude invalid combinations (like 000 or 666) using advanced regex or logic.

  • For even more robust validation, consider patterns that reject impossible SSNs by excluding area numbers like 000, 666, or any starting with 9, as well as group numbers of 00 and serial numbers of 0000.
    For example, a stricter regex would look like:

    This pattern ensures the SSN doesn't begin with prohibited sequences and avoids invalid group or serial numbers, providing an extra layer of accuracy for compliance-driven applications.

  • Avoid storing plain SSNs—encrypt them after validation.

  • Use Python Regex Tester to experiment before deploying.

  • Combine with Date Regex Python Validator if SSNs are part of a larger structured document.

For even stricter validation, consider the official rules for valid SSNs. Not every number that fits the basic "XXX-XX-XXXX" pattern is valid—certain combinations are disallowed. For example, area numbers like 000, 666, or any number starting with 9 are invalid; group numbers can't be 00; and serial numbers can't be 0000. To catch these, you can use a more advanced regex:

^(?!(0006669))\d{3}-(?!00)\d{2}-(?!0000)\d{4}$


This pattern blocks the most common invalid SSN combinations, adding an extra layer of accuracy to your validation process. While regex can handle much of the heavy lifting, remember that truly robust SSN validation sometimes requires additional logic or database checks—especially for use in regulated environments.


Potential Pitfalls of Using a Generic SSN Pattern


It might be tempting to use a relaxed regex pattern that checks for “three characters, dash (optional), three characters, dash (optional), four characters”—essentially matching any character except dashes in a 3-3-4 structure. However, this broad approach can undermine the accuracy and reliability of your validation, especially when handling sensitive information like Social Security numbers.

Here’s why you’ll want to avoid overly generic patterns for SSNs:

  • False Positives: Patterns like ^[^-]{3}-?[^-]{3}-?[^-]{4}$ will match any characters (letters, punctuation, symbols) as long as the character count fits. So, values like abc-def-ghij or X1X-X2X-X3X3 would pass—even though they’re clearly not valid SSNs.

  • Data Integrity Risks: Storing or processing mismatched data creates downstream headaches—incorrect records, failed data merges, or regulatory non-compliance.

  • Security Concerns: Loosening validation rules can allow malicious or malformed data into your systems. It exposes your application to potential exploits or information leaks.

  • Regulatory Compliance: Many industries (finance, healthcare, etc.) require strict adherence to data standards. Lenient matching could inadvertently accept and store invalid identifiers, leading to compliance violations.

For robust data validation and peace of mind, it’s always best to use a strict, digit-only pattern like ^\d{3}-\d{2}-\d{4}$. This not only enforces the classic “AAA-GG-SSSS” structure but also ensures each segment is numeric—eliminating accidental acceptance of invalid input.

Frequently asked questions

Can this regex validate both hyphenated and non-hyphenated SSNs?×
No, the current pattern (^\d{3}-\d{2}-\d{4}$) strictly matches the hyphenated format. To allow both formats, you’d need to modify the pattern to: ^\d{3}-?\d{2}-?\d{4}$.
Does this regex detect invalid or disallowed SSN combinations like 000 or 666?+
Is this pattern sufficient for use in government or financial systems?+
What if users enter leading/trailing spaces in the SSN?+
Can I use this pattern inside a larger data validation pipeline?+
Can I import Figma designs?+
Is it SEO-friendly?+
Can I collaborate with my team?+
Is hosting included?+
Can I export code?+
Is there a free plan?+
Can I use custom fonts?+

SSN Regex Python Validator

Search...

⌘K

SSN Regex Python Validator

Search...

⌘K


SSN Regex Python Validator

SSN Regex Python Validator

Validate US Social Security Numbers (SSNs) effortlessly with the SSN Regex Python Validator. This tool ensures the correct “AAA-GG-SSSS” structure using Python’s re module. Also explore Email Regex Python Validator, Phone Number Regex Python Validator, and Python Regex Tester for broader input validation.

123-45-6789
Possible security issues
This regex appears to be safe.
Explanation
  • [A-Z]: uppercase letters
  • [a-z]: lowercase letters
  • [0-9]: digits
  • \.: a literal dot
  • +: one or more of the preceding
  • *: zero or more of the preceding
  • ?: optional (zero or one)
  • ^: start of string
  • $: end of string
Test your APIs today!

Write in plain English — Qodex turns it into secure, ready-to-run tests.

SSN Regex Python Validator - Documentation

What is SSN Regex?


A Social Security Number (SSN) in the U.S. follows the standard format:

XXX-XX-XXXX


where:

  • XXX: Area number (3 digits)

  • XX: Group number (2 digits)

  • XXXX: Serial number (4 digits)


This format ensures structured identification for tax and legal purposes. Using regex helps validate whether an input string follows this format strictly.

To be considered a valid SSN, a string must also meet these specific criteria:

  • 9 digits total, separated into three parts by hyphens ().

  • First part (Area Number): 3 digits; cannot be , , or any value between and .

  • Second part (Group Number): 2 digits; must range from to (not ).

  • Third part (Serial Number): 4 digits; must range from to (not ).

These rules help ensure that only properly structured and potentially valid SSNs pass validation, reducing errors and improving data integrity.


SSN Regex Pattern


The typical regex pattern to validate a properly formatted SSN is:

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


Breakdown:

  • ^\d{3} → Three digits at the start

  • - → First hyphen separator

  • \d{2} → Two digits

  • - → Second hyphen

  • \d{4}$ → Four digits at the end


This ensures strict format matching like 123-45-6789.


Expanded Patterns and Considerations


While the above pattern covers the standard SSN format, there are a few additional scenarios and stricter checks you might consider:

  • Strict Invalid Value Exclusions:
    To avoid obviously invalid SSNs, you can use a more restrictive regex that excludes certain values:

    ^(?!(0006669))\d{3}-(?!00)\d{2}-(?!0000)\d{4}$

    • This pattern prevents area numbers of , , or any number starting with , as well as group numbers of and serial numbers of , which are not valid per official guidelines.

  • Masked or Placeholder SSNs:
    Sometimes, placeholders like are used in documentation or forms. To account for these, you can allow either a valid SSN or the placeholder:

    ^(\d{3}-\d{2}-\d{4}XXX-XX-XXXX)$

    • This matches either a real SSN or the common masked format.

  • Flexible Formatting:
    If you want to allow optional hyphens or even support lowercase or uppercase placeholders (e.g., ), consider:

    ^(\d{3}-?\d{2}-?\d{4}[Xx]{3}-?[Xx]{2}-?[Xx]{4})$

    • This pattern supports both standard and masked forms, with or without hyphens, and accepts both uppercase and lowercase 'x'.

Choose the pattern that best fits your use case—whether you need strict validation for official data entry or more lenient matching for placeholder or sample values.


What Makes an SSN Valid?


It’s not just about the pattern—there are rules beneath the surface:

  • Nine digits total: The SSN must contain exactly nine digits, split by hyphens.

  • Three parts by hyphens: The format is always .

  • Area number restrictions: The first three digits (the area number) should not be , , or any number from to .

  • Group number restrictions: The middle two digits (the group number) must be between and — is not valid.

  • Serial number restrictions: The last four digits (the serial number) should range from to — is not valid.

So, while a regex like checks the format, true SSN validation involves additional logic to ensure the number itself falls within these official boundaries. This helps catch invalid entries such as , , or , which, while matching the basic pattern, are not legitimate SSNs.

By combining regex with these additional checks, you can more confidently determine whether a given string is a valid SSN—not just a well-formatted one.


Python Example Code


import re

def is_valid_ssn(ssn):
    pattern = re.compile(r'^\d{3}-\d{2}-\d{4}$')
    return bool(pattern.fullmatch(ssn))

# Test Cases
print(is_valid_ssn("123-45-6789"))  # True
print(is_valid_ssn("123456789"))    # False
print(is_valid_ssn("12-345-6789"))  # False

Test regex variations with the Python Regex Tester.


Time and Space Complexity


Validating an SSN using a regular expression in Python is highly efficient:

  • Time Complexity: Checking a string against the SSN regex runs in O(N) time, where N is the length of the SSN string. This is because the regex engine scans through each character once to verify the format.

  • Space Complexity: The regex validation uses O(1) auxiliary space since it doesn’t require storing additional data proportional to the input size—just a handful of pattern-matching variables behind the scenes.

In practice, this means SSN validation with regex is both fast and lightweight, making it suitable for everything from web form checks to large database sweeps.


Use Cases


  • User Identity Verification: Ensure accurate SSN input during user registration or onboarding.

  • Data Cleaning: Detect and correct improperly formatted SSNs in databases.

  • Security & Compliance: Verify SSN format before transmitting sensitive data.


You can combine this with:


Regex Metacharacters Used


  • ^ : Anchors the start of the string

  • \d : Matches any digit (0–9)

  • {n} : Matches exactly n digits

  • - : Matches literal hyphens in SSNs

  • $ : Anchors the end of the string


How to Validate SSNs in JavaScript


If you need to confirm US Social Security Numbers on the frontend (or in any JavaScript-powered environment), you can use a regular expression to ensure each input follows the “AAA-GG-SSSS” convention.

Here’s a simple approach using JavaScript’s built-in RegExp:

// Regular expression for strict SSN validation
const ssnPattern = /^(?!6660009\d{2})\d{3}-(?!00)\d{2}-(?!0{4})\d{4}$/;

function isValidSSN(ssn) {
  if (!ssn) return false; // Reject empty inputs
  return ssnPattern.test(ssn);
}

// Example usage:
console.log(isValidSSN("856-45-6789")); // true (valid)
console.log(isValidSSN("000-45-6789")); // false (invalid area)
console.log(isValidSSN("856-452-6789")); // false (incorrect format)
console.log(isValidSSN("856-45-0000")); // false (invalid serial)

What the Regex Does

  • Ensures the area number (first three digits) isn’t 666, 000, or within the 900–999 range.

  • Confirms the group number (middle two digits) isn't 00.

  • Verifies the serial number (last four digits) isn’t all zeros.

  • Forces proper hyphen placement.

This pattern guards against obvious fakes and badly formatted numbers. For more advanced needs, consider combining it with additional verification (such as querying official databases), but for format validation, this approach is solid.

Test JavaScript regexes using your favorite tool—or integrate the logic above into your web forms for real-time validation.


Java Example for SSN Validation


If you need to validate SSNs in a Java application, you can use the Pattern and Matcher classes from Java's standard library. Here’s a simple way to perform strict SSN validation using regex:

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class SSNValidator {
    // Regular expression for strict SSN validation
    private static final String SSN_REGEX =
        "^(?!6660009\\d{2})\\d{3}-(?!00)\\d{2}-(?!0{4})\\d{4}$";
    private static final Pattern pattern = Pattern.compile(SSN_REGEX);

    public static boolean isValidSSN(String ssn) {
        if (ssn == null) return false;
        Matcher matcher = pattern.matcher(ssn);
        return matcher.matches();
    }

    public static void main(String[] args) {
        // Example SSNs to test
        System.out.println(isValidSSN("856-45-6789"));   // true
        System.out.println(isValidSSN("000-45-6789"));   // false
        System.out.println(isValidSSN("856-452-6789"));  // false
        System.out.println(isValidSSN("856-45-0000"));   // false
    }
}

Explanation:

  • The regex ensures the SSN does not start with "666", "000", or a number beginning with "9".

  • Group (middle) must not be "00".

  • Serial (last group) must not be "0000".

  • All other digits must match the "XXX-XX-XXXX" structure.

This approach helps catch common invalid SSNs, and you can easily expand the logic for further checks as needed.


C# Example: Validating SSNs


If you’re working with .NET or building apps in C#, you can also harness regular expressions to validate Social Security Numbers. While the approach is similar to Python, C#’s Regex class offers precise control and flexibility.

Here’s a straightforward example of SSN validation logic in C#:

using System;
using System.Text.RegularExpressions;

public class SSNValidator
{
    // Validate US SSN format and value constraints
    public static bool IsValidSSN(string ssn)
    {
        // Regex:
        // - Area numbers (first three digits) can't be 000, 666, or 900-999
        // - Group (middle two digits) can't be 00
        // - Serial (last four digits) can't be 0000
        string pattern = @"^(?!6660009\d{2})\d{3}-(?!00)\d{2}-(?!0000)\d{4}$";
        return Regex.IsMatch(ssn, pattern);
    }

    public static void Main()
    {
        var testSSNs = new[]
        {
            "856-45-6789",   // Valid
            "000-45-6789",   // Invalid area
            "856-452-6789",  // Invalid format
            "856-45-0000"    // Invalid serial
        };

        foreach (var ssn in testSSNs)
        {
            Console.WriteLine($"{ssn}: {IsValidSSN(ssn)}"

How it works:

  • The regular expression checks both the numeric structure and disallows invalid area, group, and serial numbers.

  • The IsValidSSN method returns true for valid SSNs conforming to real-world rules—not just format.

  • Run this code in any C# environment (like Visual Studio, JetBrains Rider, or online C# editors) to validate your inputs.

This follows a similar logic to the Python example above, ensuring both format and validity constraints are enforced for US Social Security Numbers.


C++ Implementation for SSN Validation


Need to validate Social Security Numbers in C++? You can apply a similar pattern-matching technique using the <regex> library. Here’s how you can perform strict SSN format checks, guarding against common invalid entries:

#include 
#include 
#include 

bool is_valid_ssn(const std::string& ssn) {
    // Pattern enforces:
    // - Area number cannot be 000, 666, or in the 900–999 range
    // - Group number cannot be 00
    // - Serial number cannot be 0000
    std::regex pattern(R"(^(?!6660009\d{2})\d{3}-(?!00)\d{2}-(?!0000)\d{4}$)");
    return std::regex_match(ssn, pattern);
}

int main() {
    std::string samples[] = {
        "856-45-6789",  // Valid
        "000-45-6789",  // Invalid (Area)
        "856-452-6789", // Invalid (Group)
        "856-45-0000"   // Invalid (Serial)
    };

    for (const auto& ssn : samples) {
        std::cout << ssn << ": " << (is_valid_ssn(ssn) ? "Valid" : "Invalid") << std::endl;
    }
    return 0;
}

This approach closely mirrors the regex logic used in Python. The regular expression works to block out prohibited values for area, group, and serial numbers per official SSN assignment rules.

  • Area Number (first three digits): Must not be 000, 666, or within the 900–999 range.

  • Group Number (middle two digits): Must not be 00.

  • Serial Number (last four digits): Must not be 0000.

With this C++ snippet, you can quickly integrate SSN validation directly into your application logic.


Matching Only Numeric or Fully Masked SSNs — Not a Mix


Sometimes, you’ll want your SSN validation to accept either fully numeric (like 123-45-6789) or fully masked (like XXX-XX-XXXX) formats—but never a combination like 12X-4X-67X9. To achieve this with regex, the trick is to build a pattern that matches either format exclusively.

Here’s how you can approach it:

  • Pattern 1 (Standard): Three digits, dash, two digits, dash, four digits:
    ^\d{3}-\d{2}-\d{4}$

  • Pattern 2 (Masked): Three Xs, dash, two Xs, dash, four Xs:
    ^[Xx]{3}-[Xx]{2}-[Xx]{4}$

To allow either the standard or masked format but not mixtures, combine them with a logical “or” using the pipe (``):

^(\d{3}-\d{2}-\d{4}[Xx]{3}-[Xx]{2}-[Xx]

This regex ensures your input is all numbers or all Xs (with dashes in place) and won’t let through strings that blend the two. You can add the case-insensitive (i) flag to let lowercase x pass, too.


Matching Numeric and Masked SSNs with Regex


To validate both real numeric SSNs and their masked counterparts (using Xs), we can craft a regex that allows either format, but not a mixture of the two.

Here's a pattern that works:

This expression will match:

  • Standard numeric SSNs: 123-45-6789

  • Fully masked SSNs: XXX-XX-XXXX

Each block must be either all digits or all uppercase Xs, preserving the familiar AAA-GG-SSSS structure with required hyphens in between. If you want to accept lowercase X (e.g., xxx-xx-xxxx), simply add the re.IGNORECASE flag in Python or use the i modifier in many regex engines.

Note: This pattern enforces a strict match—only all digits or all Xs are allowed in each respective block, not a mix. Use this approach when you need to allow for placeholder masking (common in reporting or redacted datasets) in addition to valid numeric entries.


Allowing 'X' (Upper or Lower Case) in SSN Regex


Sometimes, you might encounter scenarios where the letter 'X' is used as a placeholder within the SSN format—common in test data or anonymized records. To support both uppercase 'X' and lowercase 'x' alongside digits, you can modify your regex pattern accordingly.

Enhanced Regex Pattern:

^[\dXx]{3}-[\dXx]{2}-[\dXx]

Explanation:

  • [\dXx]: Matches any digit, 'X', or 'x' in each component of the SSN.

  • The rest of the pattern preserves the strict hyphen-separated structure.

This adjustment makes your validator flexible enough for data masking or legacy systems that substitute 'X' or 'x' for unknown SSN digits.


Using Case-Insensitive Regex for SSNs with 'x' or 'X'


Sometimes, systems allow the use of 'x' or 'X' within SSNs to mask or anonymize numbers (like 123-xx-xxxx). If you want your regex to recognize both lowercase and uppercase 'x', you can add the case-insensitive (i) flag.

For example, a pattern like ^[\dX]{3}-?[\dX]{2}-?[\dX]{4}$ with the i flag will match both 'x' and 'X'. This means:

  • 123-45-6789 is valid,

  • 123-xx-xxxx is also valid,

  • And so is 123-XX-XXXX.

Trade-Offs and Considerations


  • Broader matching: With the i flag, you’re allowing both 'x' and 'X' as placeholders anywhere digits appear.

  • Data quality: Be mindful—this opens the door for mixed-case entries (123-xX-xXxX). If you only want to allow lowercase or uppercase 'x', skip the i flag and specify your preference directly in the pattern.

  • Use cases: Accepting mask characters like 'x' may be helpful for storing partially redacted SSNs, especially when importing data from legacy systems.

If you want to offer both strict and "masked" formats, you can combine patterns:

  • One pattern for fully numeric SSNs (^\d{3}-\d{2}-\d{4}$)

  • Another for masked forms (^x{3}-x{2}-x{4}$ with or without i for case flexibility)

Just be sure to clearly communicate to users and systems what input formats are allowed, and always sanitize or validate accordingly to maintain data integrity.


Using Regex Alternatives (``) for Multiple SSN Formats


Sometimes, Social Security Numbers might appear in more than one valid format—such as the classic “123-45-6789” or as a placeholder like “XXX-XX-XXXX.” If you want your validator to accept either format, regex alternatives come in handy. The pipe character `` acts as an “or”—it lets you specify more than one pattern within a single expression.

For example, to match either a numeric SSN or its anonymized counterpart, your regex might look like:

Here’s what happens:

  • \d{3}-\d{2}-\d{4} matches a typical numerical SSN.

  • XXX-XX-XXXX matches the common masked format.

  • Parentheses group each format, and the pipe `` tells regex to accept either pattern.

  • The anchors ^ and $ make sure the entire input strictly matches one pattern or the other.

You can even expand this idea to allow for variations, like accepting both uppercase and lowercase 'x' in masked SSNs. For that, adjust the pattern to something like:

^(\d{3}-\d{2}-\d{4}[Xx]{3}-[Xx]{2}-[Xx]

This flexibility makes the pipe operator a valuable tool whenever you want to match multiple legitimate ways an SSN might appear. Now, let’s see how you might use this in Python:


Pro Tips


  • Always anchor patterns with ^ and $ to avoid partial matches.

  • Preprocess user input to trim whitespaces before validation.

  • You can extend validation to exclude invalid combinations (like 000 or 666) using advanced regex or logic.

  • For even more robust validation, consider patterns that reject impossible SSNs by excluding area numbers like 000, 666, or any starting with 9, as well as group numbers of 00 and serial numbers of 0000.
    For example, a stricter regex would look like:

    This pattern ensures the SSN doesn't begin with prohibited sequences and avoids invalid group or serial numbers, providing an extra layer of accuracy for compliance-driven applications.

  • Avoid storing plain SSNs—encrypt them after validation.

  • Use Python Regex Tester to experiment before deploying.

  • Combine with Date Regex Python Validator if SSNs are part of a larger structured document.

For even stricter validation, consider the official rules for valid SSNs. Not every number that fits the basic "XXX-XX-XXXX" pattern is valid—certain combinations are disallowed. For example, area numbers like 000, 666, or any number starting with 9 are invalid; group numbers can't be 00; and serial numbers can't be 0000. To catch these, you can use a more advanced regex:

^(?!(0006669))\d{3}-(?!00)\d{2}-(?!0000)\d{4}$


This pattern blocks the most common invalid SSN combinations, adding an extra layer of accuracy to your validation process. While regex can handle much of the heavy lifting, remember that truly robust SSN validation sometimes requires additional logic or database checks—especially for use in regulated environments.


Potential Pitfalls of Using a Generic SSN Pattern


It might be tempting to use a relaxed regex pattern that checks for “three characters, dash (optional), three characters, dash (optional), four characters”—essentially matching any character except dashes in a 3-3-4 structure. However, this broad approach can undermine the accuracy and reliability of your validation, especially when handling sensitive information like Social Security numbers.

Here’s why you’ll want to avoid overly generic patterns for SSNs:

  • False Positives: Patterns like ^[^-]{3}-?[^-]{3}-?[^-]{4}$ will match any characters (letters, punctuation, symbols) as long as the character count fits. So, values like abc-def-ghij or X1X-X2X-X3X3 would pass—even though they’re clearly not valid SSNs.

  • Data Integrity Risks: Storing or processing mismatched data creates downstream headaches—incorrect records, failed data merges, or regulatory non-compliance.

  • Security Concerns: Loosening validation rules can allow malicious or malformed data into your systems. It exposes your application to potential exploits or information leaks.

  • Regulatory Compliance: Many industries (finance, healthcare, etc.) require strict adherence to data standards. Lenient matching could inadvertently accept and store invalid identifiers, leading to compliance violations.

For robust data validation and peace of mind, it’s always best to use a strict, digit-only pattern like ^\d{3}-\d{2}-\d{4}$. This not only enforces the classic “AAA-GG-SSSS” structure but also ensures each segment is numeric—eliminating accidental acceptance of invalid input.

Frequently asked questions

Can this regex validate both hyphenated and non-hyphenated SSNs?×
No, the current pattern (^\d{3}-\d{2}-\d{4}$) strictly matches the hyphenated format. To allow both formats, you’d need to modify the pattern to: ^\d{3}-?\d{2}-?\d{4}$.
Does this regex detect invalid or disallowed SSN combinations like 000 or 666?+
Is this pattern sufficient for use in government or financial systems?+
What if users enter leading/trailing spaces in the SSN?+
Can I use this pattern inside a larger data validation pipeline?+