SSN Regex Go Validator

Search...

⌘K

SSN Regex Go Validator

Search...

⌘K


SSN Regex Go Validator

Need to verify U.S. Social Security Numbers during form validation or API testing? The Qodex SSN Regex Go Validator helps you check SSNs against standard formats instantly. Pair it with tools like the Username Generator, Phone Number Generator, or Address Generator to simulate realistic user data for testing your Go applications.

111-23-9023
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?


In Go (or Golang), regular expressions are handled via the built-in regexp package, allowing developers to match and validate text with precision.


A Social Security Number (SSN) in the U.S. has a fixed format: AAA-GG-SSSS, where:


  • AAA is the area number (3 digits)

  • GG is the group number (2 digits)

  • SSSS is the serial number (4 digits)


To validate this structure, regex provides a simple and efficient solution using the pattern:


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


This pattern ensures:

  • Three digits

  • Followed by a dash

  • Then two digits

  • Another dash

  • And four final digits


Accepting Masked SSNs

Sometimes, you may also encounter the format , often used to mask real SSNs for privacy or testing. To accommodate both standard and masked forms, you can use:

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

This matches either a valid numeric SSN or the fully masked variant.

More Accurate SSN Validation

While the above covers basic structure, real-world SSNs have additional rules. According to the , certain values are invalid—such as area numbers , , or anything beginning with , group number , or serial number . For stricter validation, consider:

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

This pattern prevents those invalid blocks while still matching the SSN format.

Supporting Flexible Input

If you want to allow optional dashes or support both uppercase and lowercase 'x' in masked SSNs, you can use:

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

Or, to simplify, add the case-insensitive flag when your language supports it.

Summary
  • Use for strict numeric SSNs.

  • Use to allow masked forms.

  • For stronger validation, use .

  • Adjust for masking and flexibility as needed by your application.

Regular expressions offer a practical way to handle SSN validation, but remember that business rules may vary, and additional checks could be necessary depending on your use case.


Example Inputs

To help you visualize what this regex catches and what it skips, here are some sample SSN-like inputs and their match results:

  • ✔️ Valid SSN format

  • ✔️ Valid, but with spaces instead of dashes

  • ✔️ Valid SSN format

  • ❌ Invalid—contains letters

  • ✔️ Valid, but may fall into restricted SSN ranges

  • ✔️ Valid pattern, but not a real SSN

  • ❌ Invalid—area number cannot be 000

This variety ensures your tests can distinguish between properly formatted SSNs, common input mistakes, and outright invalid entries. Use these examples to fine-tune your validation or to seed realistic test data during development.


Understanding Regex Flags


When working with regular expressions in Go or JavaScript, you’ll often come across flags that modify how your patterns behave. Here’s a quick reference to the most common ones:

  • g (global): Searches for all matches in the text, not just the first one.

  • i (ignore case): Makes the match case-insensitive, treating uppercase and lowercase letters as equal.

  • m (multiline): Changes the behavior of ^ and $ so they match at the start and end of each line, rather than just the start and end of the string.

  • s (dotAll): Allows the dot (.) to match newline characters, so your pattern can span multiple lines.

  • u (unicode): Enables full Unicode matching, making it easier to handle emoji and characters from non-English scripts.

  • y (sticky): Matches only at the last index where the previous match ended, helpful for iterating through a string one match at a time.

Each flag tailors your regex to suit specific validation or searching needs, so it’s worth experimenting to see which combination fits your use case best.


How Invalid SSNs Are Blocked


Not all combinations are valid for U.S. Social Security Numbers—and the regex pattern is smart enough to catch common invalid formats. Here’s how it guards against bogus entries:

  • No All-Zero Groups: The regex won’t accept any SSN where a full group is zeroed out, like , , or . This protects against placeholders and unrealistic numbers.

  • No 666 Starts: Any SSN beginning with is always rejected—this sequence is never assigned to real SSNs.

  • No 900–999 Ranges: The pattern also rules out SSNs starting with through , which are reserved and not valid for standard identification.

Thanks to these checks, you minimize the risk of processing obviously fake or reserved SSNs, helping your apps and API endpoints remain secure and reliable.


Pattern for Real and Masked SSNs


What if you need to accept both genuine SSNs and masked placeholders (using Xs)? This is common when dealing with redacted data for privacy reasons or placeholder inputs during testing.

You can achieve this by expanding your regular expression to handle either all-numeric SSNs or those with Xs in place of numbers. For example, here's how you can build such a pattern:

  • Match standard SSNs: ^\d{3}-\d{2}-\d{4}$

  • Match masked SSNs: ^X{3}-X{2}-X{4}$

To allow either format, combine them using the OR operator in your regex:

Prefer a bit more flexibility? You can also make your regex case-insensitive if you want to accept lowercase "x" as well as uppercase "X":

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

This pattern ensures only fully numeric or fully masked SSNs are accepted—never a mix of numbers and Xs within the same match. For even stricter real-world compliance, you might enforce additional rules (like disallowing area numbers 000, 666, or beginning with 9), but for most testing and masking scenarios, this approach will work seamlessly.


Going Beyond the Basics: More Accurate SSN Validation


However, if you want your validation to be more than just format checking, there are additional rules around what constitutes a valid SSN. For example, certain numbers are not issued:

  • The area number (AAA) cannot be "000", "666", or any value starting with "9".

  • The group number (GG) cannot be "00".

  • The serial number (SSSS) cannot be "0000".

To capture these extra rules and avoid most invalid SSNs, you can use a more precise regex:
^(?!(0006669))\d{3}-(?!00)\d{2}-(?!0000)\d{4}$
This enhanced pattern helps weed out obviously invalid SSNs while still keeping your validation logic all in one place—no extra code required.
Use whichever regex best suits your needs: simple format validation or stricter compliance with real-world SSN assignment rules.

Customizing the Regex for Test-Friendly SSNs


Sometimes, you need SSNs for testing that don’t use real data—many teams prefer using “X” placeholders instead of digits, like XXX-XX-XXXX. To accommodate this, you can expand the regex to allow either all digits in each section or all “X”s. Here’s how it works:

  • Use \d{3}-\d{2}-\d{4} to match a standard numeric SSN.

  • Use [Xx]{3}-[Xx]{2}-[Xx]{4} to match a completely “X”-filled SSN (accepting both uppercase and lowercase X).

Important: To keep your validation strict and prevent mixing “X”s and digits within the same SSN (such as 12X-4X-98X3), the regex should enforce one style or the other, not a blend.

The combined pattern looks like this:

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

This setup accepts either a fully numeric SSN or one with all “X”s in place of digits, but never a mix in different positions. If you want to accept only “X”s for placeholders, stick with the [Xx]{3}-[Xx]{2}-[Xx]{4} pattern.

If your team needs additional flexibility (for example, allowing both “X”s and digits mixed within groups), you can modify each group to accept digits or “X”s like this:

^([0-9Xx]{3}-[0-9Xx]{2}-[0-9Xx]

However, for most testing and validation scenarios, sticking with the "all-digits or all-Xs" approach helps avoid accidental exposure of real data and keeps things predictable for both humans and automated systems.


How to Support Masked SSNs in Your Regex


Sometimes, you need to accommodate masked Social Security Numbers—where some or all digits are replaced with "X" or "x" for privacy (e.g., "XXX-XX-9023" or "xxx-xx-xxxx"). To handle this, the regular expression must recognize either a fully numeric SSN or a version where each section can be replaced by Xs.

Here's how you can expand your regex to allow both formats:

  • Full numeric SSN: 123-45-6789

  • Fully masked: XXX-XX-XXXX (also accepts lowercase x)

  • Note: Each segment should be either all digits or all Xs.

To accommodate both styles, you can use:

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

This pattern does the following:

  • Matches either the standard numeric SSN format

  • Or a version where every digit is consistently replaced by "X" or "x"

  • Ensures proper section lengths and dash placement

Quick Tips:

  • For even more flexibility, add case-insensitive matching if your tool supports it.

  • Avoid mixing digits and Xs within any single segment to maintain consistent formatting and security.

Now your Go-powered validator is ready to recognize both real and masked SSNs, making it easier to test, anonymize, or display sensitive data securely.


Combining Multiple SSN Formats in One Regex


Sometimes, you need a regex that covers more than just one standard SSN structure. For example, maybe your application accepts both validly formatted SSNs (like 123-45-6789) and placeholder values (such as XXX-XX-XXXX)—which are common in testing, data masking, or sample datasets.

To capture both possibilities in a single pattern, you can use a logical OR (``) in your regex. Here’s how that looks in practice:

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

This pattern matches:

  • Properly formatted SSNs with digits (e.g., 111-22-3333)

  • Placeholder versions using either uppercase or lowercase X (e.g., XXX-XX-XXXX or xxx-xx-xxxx)

You can even extend the regex by making it case-insensitive, so [Xx] is handled automatically. In Go’s regexp package, patterns are always case sensitive, so you’d need [Xx] instead of just X.

Summary of pattern logic:

  • \d{3}-\d{2}-\d{4}: Matches a standard SSN format.

  • [Xx]{3}-[Xx]{2}-[Xx]{4}: Matches an anonymized placeholder in either lowercase or uppercase.

If your use case has additional variations (for example, optionally omitting the dashes), you can adjust the regex to include -? after each numeric or X block. For most validation workflows that cover real and dummy data, the above pattern provides a robust solution.

Now, let’s look at what makes this regex reliable for validation in your Go projects:


Matching Any 3-2-4 Pattern with Dashes


Sometimes, you might want to validate inputs that use the same 3-2-4 format as an SSN, but aren’t actually restricted to just digits. To allow any character except dashes in those positions, you can use a flexible regular expression:

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

Here’s how this pattern works:

  • [^-]{3}: Exactly three characters, each one not a dash (-)

  • -: A literal dash as separator

  • [^-]{2}: Two more characters, again anything except a dash

  • -: Another literal dash

  • [^-]{4}: Four final characters, none of which are dashes

This structure matches any string that follows a 3-2-4 pattern separated by dashes, whether the characters are letters, symbols, or numbers (just not dashes themselves).

Example matches:

  • abc-de-fghi

  • 1a2-34-5678

  • XYZ-tt-9*1!

Keep in mind: This allows broad matching—use it only if you truly want to accept any character except the dash in those positions (rather than just digits).


Core Features & Benefits


  • Format-Specific: Strictly enforces U.S. SSN format.

  • Instant Validation: Works immediately in Go with regexp.MustCompile.

  • Safe Testing: Avoid using real data—test your systems with dummy values.

  • Reusable Regex: Easily incorporate this pattern into your Go codebase.

  • Compatible with Multiple Tools: Works great with UUID Generator, MAC Address Generator, and Phone Number Regex Go Validator for full simulation.



Example Code in Go


package main

import (
    "fmt"
    "regexp"
)

func isValidSSN(ssn string) bool {
    // Regex for U.S. SSN: 3 digits - 2 digits - 4 digits
    var ssnRegex = regexp.MustCompile(`^\d{3}-\d{2}-\d{4}$`)
    return ssnRegex.MatchString(ssn)
}

func main() {
    testSSN := "123-45-6789"
    fmt.Printf("Is '%s' a valid SSN? %t\n", testSSN, isValidSSN(testSSN))
}


Making Your Regex Case-Insensitive

To match both uppercase and lowercase "X" in masked SSNs—like "XXX-XX-1234" or "xxx-xx-1234"—you have two options:

  • Include both cases in your pattern with [Xx] wherever the mask appears.

  • Use the case-insensitive flag (i), if your Go regex context supports it.

For Go’s regexp package, you'll need to specify [Xx] in the regex, since Go does not support an inline case-insensitive flag. This ensures your validation covers all common masked SSN formats without missing a beat.


Pro Tips for Using SSN Regex in Go


  • Use Anchors for Full Match: Always wrap your regex with ^ and $ to ensure the entire string is validated and not just a substring.

  • Avoid Real Data in Tests: Never use actual SSNs in testing environments. Instead, simulate them using tools like the Username Generator, Phone Number Generator, or Address Generator to create complete mock profiles.

  • Precompile for Performance: Use regexp.MustCompile() outside of loops or functions to precompile your regex and improve performance, especially in large-scale apps.

  • Validate Format, Not Identity: Regex only checks structure. To validate real SSNs, integrate with a verification API or official database.

  • Use Logging for Debugging: While testing your Go regex logic, add logs to track matches and mismatches. This will help catch formatting issues early.


Going Beyond Basic Validation


While a simple pattern like covers most formatting needs, it doesn't capture all the rules that make an SSN truly valid. For more robust validation, consider a stricter regex:

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

This pattern adds real-world restrictions:

  • No area numbers starting with , , or .

  • No group numbers of .

  • No serial numbers of .

Referencing sources like the SSA guidelines or Wikipedia’s “Valid SSNs” section can help ensure your validation logic follows official standards. Remember, these restrictions make your validation stronger but still don't guarantee the number is assigned or belongs to a real person.

If you need to support obvious test data (like or ), you can also expand your pattern:

^(123-45-6789XXX-XX-XXXX(?!(0006669))\d{3}-(?!00)\d{2}-(?!0000)\d{4})$

This allows for commonly used dummy SSNs in addition to real-world format validation.

With these tips and stricter patterns, your Go applications can catch more invalid SSNs before they hit your systems, while still keeping your validation logic clear and maintainable.


Common Use Cases


  • Form Validation: Ensure users enter SSNs in the correct format.

  • Onboarding Systems: Verify identification during user registration.

  • Data Cleansing: Clean up and standardize SSN fields in your database.

  • Compliance Systems: Enforce format validation for privacy-sensitive workflows.


You’ll also find these regex basics useful:


Expression What it matches Any digit (equivalent to ) The word "hello" repeated 1 to 3 times consecutively The beginning of a line or string The end of a line or string These elements are essential when crafting patterns to match Social Security Numbers or any structured data in your Go applications.


Combine With These Tools


Use the SSN Validator with these Qodex tools for complete profile simulation and testing:



Regex for Other Languages


Want to test SSNs in other languages?


Frequently asked questions

Can this regex check if an SSN is real?×
No, it only checks if the SSN is correctly formatted—not whether it’s issued or valid.
Why use regex for SSN validation in Go?+
What if someone enters an SSN without dashes?+
Is it safe to store SSNs after validating them?+
Can this be used in production systems?+
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 Go Validator

Search...

⌘K

SSN Regex Go Validator

Search...

⌘K


SSN Regex Go Validator

SSN Regex Go Validator

Need to verify U.S. Social Security Numbers during form validation or API testing? The Qodex SSN Regex Go Validator helps you check SSNs against standard formats instantly. Pair it with tools like the Username Generator, Phone Number Generator, or Address Generator to simulate realistic user data for testing your Go applications.

111-23-9023
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 Go Validator - Documentation

What is SSN Regex?


In Go (or Golang), regular expressions are handled via the built-in regexp package, allowing developers to match and validate text with precision.


A Social Security Number (SSN) in the U.S. has a fixed format: AAA-GG-SSSS, where:


  • AAA is the area number (3 digits)

  • GG is the group number (2 digits)

  • SSSS is the serial number (4 digits)


To validate this structure, regex provides a simple and efficient solution using the pattern:


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


This pattern ensures:

  • Three digits

  • Followed by a dash

  • Then two digits

  • Another dash

  • And four final digits


Accepting Masked SSNs

Sometimes, you may also encounter the format , often used to mask real SSNs for privacy or testing. To accommodate both standard and masked forms, you can use:

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

This matches either a valid numeric SSN or the fully masked variant.

More Accurate SSN Validation

While the above covers basic structure, real-world SSNs have additional rules. According to the , certain values are invalid—such as area numbers , , or anything beginning with , group number , or serial number . For stricter validation, consider:

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

This pattern prevents those invalid blocks while still matching the SSN format.

Supporting Flexible Input

If you want to allow optional dashes or support both uppercase and lowercase 'x' in masked SSNs, you can use:

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

Or, to simplify, add the case-insensitive flag when your language supports it.

Summary
  • Use for strict numeric SSNs.

  • Use to allow masked forms.

  • For stronger validation, use .

  • Adjust for masking and flexibility as needed by your application.

Regular expressions offer a practical way to handle SSN validation, but remember that business rules may vary, and additional checks could be necessary depending on your use case.


Example Inputs

To help you visualize what this regex catches and what it skips, here are some sample SSN-like inputs and their match results:

  • ✔️ Valid SSN format

  • ✔️ Valid, but with spaces instead of dashes

  • ✔️ Valid SSN format

  • ❌ Invalid—contains letters

  • ✔️ Valid, but may fall into restricted SSN ranges

  • ✔️ Valid pattern, but not a real SSN

  • ❌ Invalid—area number cannot be 000

This variety ensures your tests can distinguish between properly formatted SSNs, common input mistakes, and outright invalid entries. Use these examples to fine-tune your validation or to seed realistic test data during development.


Understanding Regex Flags


When working with regular expressions in Go or JavaScript, you’ll often come across flags that modify how your patterns behave. Here’s a quick reference to the most common ones:

  • g (global): Searches for all matches in the text, not just the first one.

  • i (ignore case): Makes the match case-insensitive, treating uppercase and lowercase letters as equal.

  • m (multiline): Changes the behavior of ^ and $ so they match at the start and end of each line, rather than just the start and end of the string.

  • s (dotAll): Allows the dot (.) to match newline characters, so your pattern can span multiple lines.

  • u (unicode): Enables full Unicode matching, making it easier to handle emoji and characters from non-English scripts.

  • y (sticky): Matches only at the last index where the previous match ended, helpful for iterating through a string one match at a time.

Each flag tailors your regex to suit specific validation or searching needs, so it’s worth experimenting to see which combination fits your use case best.


How Invalid SSNs Are Blocked


Not all combinations are valid for U.S. Social Security Numbers—and the regex pattern is smart enough to catch common invalid formats. Here’s how it guards against bogus entries:

  • No All-Zero Groups: The regex won’t accept any SSN where a full group is zeroed out, like , , or . This protects against placeholders and unrealistic numbers.

  • No 666 Starts: Any SSN beginning with is always rejected—this sequence is never assigned to real SSNs.

  • No 900–999 Ranges: The pattern also rules out SSNs starting with through , which are reserved and not valid for standard identification.

Thanks to these checks, you minimize the risk of processing obviously fake or reserved SSNs, helping your apps and API endpoints remain secure and reliable.


Pattern for Real and Masked SSNs


What if you need to accept both genuine SSNs and masked placeholders (using Xs)? This is common when dealing with redacted data for privacy reasons or placeholder inputs during testing.

You can achieve this by expanding your regular expression to handle either all-numeric SSNs or those with Xs in place of numbers. For example, here's how you can build such a pattern:

  • Match standard SSNs: ^\d{3}-\d{2}-\d{4}$

  • Match masked SSNs: ^X{3}-X{2}-X{4}$

To allow either format, combine them using the OR operator in your regex:

Prefer a bit more flexibility? You can also make your regex case-insensitive if you want to accept lowercase "x" as well as uppercase "X":

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

This pattern ensures only fully numeric or fully masked SSNs are accepted—never a mix of numbers and Xs within the same match. For even stricter real-world compliance, you might enforce additional rules (like disallowing area numbers 000, 666, or beginning with 9), but for most testing and masking scenarios, this approach will work seamlessly.


Going Beyond the Basics: More Accurate SSN Validation


However, if you want your validation to be more than just format checking, there are additional rules around what constitutes a valid SSN. For example, certain numbers are not issued:

  • The area number (AAA) cannot be "000", "666", or any value starting with "9".

  • The group number (GG) cannot be "00".

  • The serial number (SSSS) cannot be "0000".

To capture these extra rules and avoid most invalid SSNs, you can use a more precise regex:
^(?!(0006669))\d{3}-(?!00)\d{2}-(?!0000)\d{4}$
This enhanced pattern helps weed out obviously invalid SSNs while still keeping your validation logic all in one place—no extra code required.
Use whichever regex best suits your needs: simple format validation or stricter compliance with real-world SSN assignment rules.

Customizing the Regex for Test-Friendly SSNs


Sometimes, you need SSNs for testing that don’t use real data—many teams prefer using “X” placeholders instead of digits, like XXX-XX-XXXX. To accommodate this, you can expand the regex to allow either all digits in each section or all “X”s. Here’s how it works:

  • Use \d{3}-\d{2}-\d{4} to match a standard numeric SSN.

  • Use [Xx]{3}-[Xx]{2}-[Xx]{4} to match a completely “X”-filled SSN (accepting both uppercase and lowercase X).

Important: To keep your validation strict and prevent mixing “X”s and digits within the same SSN (such as 12X-4X-98X3), the regex should enforce one style or the other, not a blend.

The combined pattern looks like this:

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

This setup accepts either a fully numeric SSN or one with all “X”s in place of digits, but never a mix in different positions. If you want to accept only “X”s for placeholders, stick with the [Xx]{3}-[Xx]{2}-[Xx]{4} pattern.

If your team needs additional flexibility (for example, allowing both “X”s and digits mixed within groups), you can modify each group to accept digits or “X”s like this:

^([0-9Xx]{3}-[0-9Xx]{2}-[0-9Xx]

However, for most testing and validation scenarios, sticking with the "all-digits or all-Xs" approach helps avoid accidental exposure of real data and keeps things predictable for both humans and automated systems.


How to Support Masked SSNs in Your Regex


Sometimes, you need to accommodate masked Social Security Numbers—where some or all digits are replaced with "X" or "x" for privacy (e.g., "XXX-XX-9023" or "xxx-xx-xxxx"). To handle this, the regular expression must recognize either a fully numeric SSN or a version where each section can be replaced by Xs.

Here's how you can expand your regex to allow both formats:

  • Full numeric SSN: 123-45-6789

  • Fully masked: XXX-XX-XXXX (also accepts lowercase x)

  • Note: Each segment should be either all digits or all Xs.

To accommodate both styles, you can use:

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

This pattern does the following:

  • Matches either the standard numeric SSN format

  • Or a version where every digit is consistently replaced by "X" or "x"

  • Ensures proper section lengths and dash placement

Quick Tips:

  • For even more flexibility, add case-insensitive matching if your tool supports it.

  • Avoid mixing digits and Xs within any single segment to maintain consistent formatting and security.

Now your Go-powered validator is ready to recognize both real and masked SSNs, making it easier to test, anonymize, or display sensitive data securely.


Combining Multiple SSN Formats in One Regex


Sometimes, you need a regex that covers more than just one standard SSN structure. For example, maybe your application accepts both validly formatted SSNs (like 123-45-6789) and placeholder values (such as XXX-XX-XXXX)—which are common in testing, data masking, or sample datasets.

To capture both possibilities in a single pattern, you can use a logical OR (``) in your regex. Here’s how that looks in practice:

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

This pattern matches:

  • Properly formatted SSNs with digits (e.g., 111-22-3333)

  • Placeholder versions using either uppercase or lowercase X (e.g., XXX-XX-XXXX or xxx-xx-xxxx)

You can even extend the regex by making it case-insensitive, so [Xx] is handled automatically. In Go’s regexp package, patterns are always case sensitive, so you’d need [Xx] instead of just X.

Summary of pattern logic:

  • \d{3}-\d{2}-\d{4}: Matches a standard SSN format.

  • [Xx]{3}-[Xx]{2}-[Xx]{4}: Matches an anonymized placeholder in either lowercase or uppercase.

If your use case has additional variations (for example, optionally omitting the dashes), you can adjust the regex to include -? after each numeric or X block. For most validation workflows that cover real and dummy data, the above pattern provides a robust solution.

Now, let’s look at what makes this regex reliable for validation in your Go projects:


Matching Any 3-2-4 Pattern with Dashes


Sometimes, you might want to validate inputs that use the same 3-2-4 format as an SSN, but aren’t actually restricted to just digits. To allow any character except dashes in those positions, you can use a flexible regular expression:

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

Here’s how this pattern works:

  • [^-]{3}: Exactly three characters, each one not a dash (-)

  • -: A literal dash as separator

  • [^-]{2}: Two more characters, again anything except a dash

  • -: Another literal dash

  • [^-]{4}: Four final characters, none of which are dashes

This structure matches any string that follows a 3-2-4 pattern separated by dashes, whether the characters are letters, symbols, or numbers (just not dashes themselves).

Example matches:

  • abc-de-fghi

  • 1a2-34-5678

  • XYZ-tt-9*1!

Keep in mind: This allows broad matching—use it only if you truly want to accept any character except the dash in those positions (rather than just digits).


Core Features & Benefits


  • Format-Specific: Strictly enforces U.S. SSN format.

  • Instant Validation: Works immediately in Go with regexp.MustCompile.

  • Safe Testing: Avoid using real data—test your systems with dummy values.

  • Reusable Regex: Easily incorporate this pattern into your Go codebase.

  • Compatible with Multiple Tools: Works great with UUID Generator, MAC Address Generator, and Phone Number Regex Go Validator for full simulation.



Example Code in Go


package main

import (
    "fmt"
    "regexp"
)

func isValidSSN(ssn string) bool {
    // Regex for U.S. SSN: 3 digits - 2 digits - 4 digits
    var ssnRegex = regexp.MustCompile(`^\d{3}-\d{2}-\d{4}$`)
    return ssnRegex.MatchString(ssn)
}

func main() {
    testSSN := "123-45-6789"
    fmt.Printf("Is '%s' a valid SSN? %t\n", testSSN, isValidSSN(testSSN))
}


Making Your Regex Case-Insensitive

To match both uppercase and lowercase "X" in masked SSNs—like "XXX-XX-1234" or "xxx-xx-1234"—you have two options:

  • Include both cases in your pattern with [Xx] wherever the mask appears.

  • Use the case-insensitive flag (i), if your Go regex context supports it.

For Go’s regexp package, you'll need to specify [Xx] in the regex, since Go does not support an inline case-insensitive flag. This ensures your validation covers all common masked SSN formats without missing a beat.


Pro Tips for Using SSN Regex in Go


  • Use Anchors for Full Match: Always wrap your regex with ^ and $ to ensure the entire string is validated and not just a substring.

  • Avoid Real Data in Tests: Never use actual SSNs in testing environments. Instead, simulate them using tools like the Username Generator, Phone Number Generator, or Address Generator to create complete mock profiles.

  • Precompile for Performance: Use regexp.MustCompile() outside of loops or functions to precompile your regex and improve performance, especially in large-scale apps.

  • Validate Format, Not Identity: Regex only checks structure. To validate real SSNs, integrate with a verification API or official database.

  • Use Logging for Debugging: While testing your Go regex logic, add logs to track matches and mismatches. This will help catch formatting issues early.


Going Beyond Basic Validation


While a simple pattern like covers most formatting needs, it doesn't capture all the rules that make an SSN truly valid. For more robust validation, consider a stricter regex:

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

This pattern adds real-world restrictions:

  • No area numbers starting with , , or .

  • No group numbers of .

  • No serial numbers of .

Referencing sources like the SSA guidelines or Wikipedia’s “Valid SSNs” section can help ensure your validation logic follows official standards. Remember, these restrictions make your validation stronger but still don't guarantee the number is assigned or belongs to a real person.

If you need to support obvious test data (like or ), you can also expand your pattern:

^(123-45-6789XXX-XX-XXXX(?!(0006669))\d{3}-(?!00)\d{2}-(?!0000)\d{4})$

This allows for commonly used dummy SSNs in addition to real-world format validation.

With these tips and stricter patterns, your Go applications can catch more invalid SSNs before they hit your systems, while still keeping your validation logic clear and maintainable.


Common Use Cases


  • Form Validation: Ensure users enter SSNs in the correct format.

  • Onboarding Systems: Verify identification during user registration.

  • Data Cleansing: Clean up and standardize SSN fields in your database.

  • Compliance Systems: Enforce format validation for privacy-sensitive workflows.


You’ll also find these regex basics useful:


Expression What it matches Any digit (equivalent to ) The word "hello" repeated 1 to 3 times consecutively The beginning of a line or string The end of a line or string These elements are essential when crafting patterns to match Social Security Numbers or any structured data in your Go applications.


Combine With These Tools


Use the SSN Validator with these Qodex tools for complete profile simulation and testing:



Regex for Other Languages


Want to test SSNs in other languages?


Frequently asked questions

Can this regex check if an SSN is real?×
No, it only checks if the SSN is correctly formatted—not whether it’s issued or valid.
Why use regex for SSN validation in Go?+
What if someone enters an SSN without dashes?+
Is it safe to store SSNs after validating them?+
Can this be used in production systems?+