SSN Regex Javascript Validator
Search...
⌘K
SSN Regex Javascript Validator
Search...
⌘K


SSN Regex Javascript Validator
Easily validate U.S. Social Security Numbers using our JavaScript Regex Tester. This tool ensures your input follows the standard XXX-XX-XXXX format. Whether you’re building secure onboarding flows or cleaning form data, pair it with our Base64 Encoder to protect sensitive info, or convert bulk files using the CSV to JSON Converter. Fast, accurate, and perfect for developers handling identity data.
[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 an SSN Regex?
In the U.S., a Social Security Number (SSN) is a 9-digit number formatted as XXX-XX-XXXX. Validating this format is crucial in applications where identity verification or data entry accuracy is required.
A regular expression (regex) helps ensure the format is correct before any sensitive operations are performed.
Common SSN Regex Pattern
/^\d{3}-\d{2}-\d{4}$/
What This Pattern Does:
^\d{3}
: Start with exactly 3 digits-
: A hyphen\d{2}
: Followed by 2 digits-
: Another hyphen\d{4}$
: Ends with 4 digits
Valid SSN: 123-45-6789
Invalid SSN: 12-3456-789 or 123456789
A More Accurate SSN Regex
While the above pattern matches the standard SSN format, it doesn't catch all invalid possibilities. Certain combinations—like area numbers starting with 000, 666, or 9, or groups like 00 or 0000—aren't valid for real Social Security Numbers.
If you need a stricter check, consider this pattern:
^(?!(0006669))\d{3}-(?!00)\d{2}-(?!0000)\d{4}$
What’s Improved Here:
: Ensures the area number (the first three digits) is not 000, 666, or any number starting with 9.
: The group number (middle two digits) can’t be 00.
: The serial number (last four digits) can’t be 0000.
This extra layer helps weed out obviously invalid SSNs while still matching the correct format.
Example of valid SSN: 123-45-6789
Examples of invalid SSNs: 000-12-3456, 666-12-3456, 900-12-3456, 123-00-4567, 123-45-0000
Use the stricter pattern if you want to more closely mirror real-world SSN rules, but remember: even the best regex can't guarantee a number is actually issued to a real person.
A More Flexible Pattern for Custom Formats
If you’d like a regex that matches any groupings of non-hyphen characters following the familiar 3-2-4 split (but without requiring digits), you can tweak the pattern like so:
^[^-]{3}-?[^-]{2}-?[^-]
How This Pattern Works:
^[^-]{3}
: Start with exactly 3 characters that aren’t hyphens-?
: An optional hyphen[^-]{2}
: Next, 2 non-hyphen characters-?
: Another optional hyphen[^-]{4}$
: Finally, 4 non-hyphen characters
This is handy if you’re dealing with codes or IDs—such as ABC-DE-1234
or XyZ12aBcd
—that aren’t strictly numeric but still fit the 3-2-4 structure (with or without hyphens).
Examples matched:
ABC-DE-1234
xyz12abcd
B2C-D1-42k7
Examples not matched:
AB-DE-1234
(only 2 characters at the start)ABC--DE-1234
(contains double hyphens)A-BC-DE-1234
(incorrect grouping)
Feel free to adjust the numbers if your format varies!
Matching Both Numeric and Masked SSN Formats
If you want your regex to accept both standard numeric SSNs and those that use 'X' characters for masking (like XXX-XX-XXXX
), you'll just need to expand your pattern a bit.
Updated Regex Pattern
^(\d{3}-\d{2}-\d{4}[Xx]{3}-[Xx]{2}-[Xx]
What This Updated Pattern Does:
\d{3}-\d{2}-\d{4}
: Matches three digits, a hyphen, two digits, a hyphen, and four digits—just like before.[Xx]{3}-[Xx]{2}-[Xx]{4}
: Matches three Xs (upper or lowercase), a hyphen, two Xs, a hyphen, and four Xs.The pipe (``) lets you match either the numeric or masked version, but not a mix of both.
The
^
and$
match the start and end of the string to ensure the full SSN is validated.
Examples
Valid Numeric SSN: 123-45-6789
Valid Masked SSN: XXX-XX-XXXX or xxx-xx-xxxx
Invalid Mixed: 123-XX-6789
With this, you can confidently accept either the real SSN or the masked placeholder—no more watching for sneaky combinations!
Strict Pattern: Only Allowing 123-45-6789 or XXX-XX-XXXX
If you need a regex that matches only the specific SSNs 123-45-6789
or XXX-XX-XXXX
, here's what you need:
^
and$
ensure the pattern matches the entire string from start to finish.The pipe (``) acts as an "or," so it allows either
123-45-6789
orXXX-XX-XXXX
—nothing else.
Any input besides those two exact formats will be rejected.
Combining Multiple SSN Formats with Alternation
Suppose you need to accept both standard SSNs (numbers only) and placeholder formats (like all X's) in your regex. This is where alternation comes in handy. Alternation allows your regex to match either one pattern or another using the pipe character (``).
For example, let's say you want to allow:
Standard numeric SSNs:
123-45-6789
Placeholder SSNs:
XXX-XX-XXXX
You can combine them like this:
What this does:
The `` symbol means "or," so the regex will match if the input fits either the numeric pattern or the all-X pattern.
The parentheses group the alternatives, ensuring the regex matches the structure of either option from start to finish.
You can further adapt this pattern to allow flexibility, such as matching lowercase x with [Xx]
:
/^(\d{3}-\d{2}-\d{4}[Xx]{3}-[Xx]{2}-[Xx]
This way, entries like xxx-xx-xxxx
are also accepted. Use the i
flag (for case-insensitive matching) if your regex flavor supports it—making life even simpler.
So, with a single, well-structured regex and a bit of alternation, you can seamlessly validate multiple SSN formats in one go.
Allowing All Digits or All Xs (But Not Mixed) in SSN Regex
Suppose you want your SSN input to accept either the standard all-digit version (123-45-6789
) or a masked version using just Xs (XXX-XX-XXXX
), but never a mixture of the two. Here’s how you can do it:
Regex Breakdown
To achieve this, you’ll use the `` (pipe) operator, which means "or," and group patterns for clarity:
The first pattern matches only digits in the SSN format:
^\d{3}-\d{2}-\d{4}$
The second pattern matches only Xs (case-insensitive), same format:
^[Xx]{3}-[Xx]{2}-[Xx]{4}$
Combine them like so:
/^(\d{3}-\d{2}-\d{4}[Xx]{3}-[Xx]{2}-[Xx]
Or, if your language supports it, you can use the case-insensitive flag (i
) so you only need [X]{3}-[X]{2}-[X]{4}
.
What Does This Do?
Digits-only allowed:
123-45-6789
Xs-only allowed:
XXX-XX-XXXX
(accepts both uppercase and lowercase X)No mixing: Patterns like
12X-4X-6789
will not match
This keeps input consistent and secure, especially for forms masking sensitive information.
Tip: To relax about hyphens (e.g., optional hyphens), replace -
with -?
in both alternatives.
With this approach, your form or validator strictly allows either genuine numeric SSNs or fully redacted ones—never a blended masquerade.
SSN Validation: Beyond the Basics
While matching the XXX-XX-XXXX format is a good start, a truly valid SSN must also meet a few more specific criteria:
9 Digits Only: The SSN must have exactly 9 digits, no more, no less.
Hyphenated in 3 Parts: The number is always split into three parts by hyphens: the first part (3 digits), the second part (2 digits), and the third part (4 digits).
First Part Restrictions: The first three digits cannot be , , or any number in the range .
Second Part Range: The middle two digits must be between and — is not valid.
Third Part Range: The last four digits must be between and — is not valid.
For example, while is valid, numbers like , , or would fail these checks.
By combining regex formatting and these additional rules, you can more confidently validate SSNs and filter out invalid or potentially fraudulent entries.
Performance Considerations
When it comes to validating an SSN with this regex pattern, the process examines each character in the input string once, making the time complexity linear—O(N), where N is the number of characters. The space requirements are minimal, as the regex engine does not need extra memory proportional to the size of the input. In short, you get efficient validation both in speed and memory use.
How to Validate SSNs in JavaScript
Here’s a complete JavaScript code example:
function isValidSSN(ssn) { const ssnRegex = /^\d{3}-\d{2}-\d{4}$/; return ssnRegex.test(ssn); } // Example usage: console.log(isValidSSN("123-45-6789")); // true console.log(isValidSSN("123456789")); // false
How to Validate SSNs in Python
Need to ensure SSNs fit the proper mold in your Python application? Let's walk through an easy approach using regular expressions—great for backend checks or data migrations.
Here's a typical function to validate SSN format in Python:
import re def is_valid_ssn(ssn): pattern = r"^(?!6660009\d{2})\d{3}-(?!00)\d{2}-(?!0000)\d{4}$" return bool(re.match(pattern, ssn))
How it works:
^(?!6660009\d{2})\d{3}
: The SSN can't start with 666, 000, or any number between 900-999.-(?!00)\d{2}
: The middle two digits can't be 00.-(?!0000)\d{4}$
: The last four digits can't be 0000.
Examples:
print(is_valid_ssn("856-45-6789")) # True – valid SSN print(is_valid_ssn("000-45-6789")) # False – invalid, leading block not allowed print(is_valid_ssn("856-452-6789")) # False – wrong format print(is_valid_ssn("856-45-0000")) # False – trailing block not allowed
This approach quickly weeds out most SSN format issues and can easily be adapted for batch processing or user input validation. For extra protection, pair this with secure storage solutions—never keep SSNs in plain sight!
How to Validate SSNs Using Regex in Java
Just like in JavaScript, you can also use a regular expression in Java to check Social Security Number formats efficiently—and even add a bit more rigor.
Here’s what a typical validation function looks like in Java:
import java.util.regex.Pattern; public class SSNValidator { // Pattern blocks obviously invalid ranges (000, 666, 900–999 in the first group; 00 in the middle; 0000 at the end) private static final Pattern SSN_REGEX = Pattern.compile( "^(?!6660009\\d{2})\\d{3}-(?!00)\\d{2}-(?!0{4})\\d{4}$" ); public static boolean isValidSSN(String ssn) { if (ssn == null) return false; return SSN_REGEX.matcher(ssn).matches(); } // Example usage public static void main(String[] args) { 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 } }
How it Works:
The regex prevents common invalid SSNs, such as those starting with 666, 000, or any 900–999 series, as well as entries with all zeros in the middle or end.
The function returns
true
only if the input matches both SSN format and these stricter rules.As always, make sure to check for
null
before attempting the match to avoid exceptions.
This approach provides an extra layer of safety, catching not only mistyped formats but also values explicitly blocked by the Social Security Administration.
Where Can SSN Regex Be Used?
User Onboarding: Ensure users enter valid SSNs in financial or HR applications.
Database Integrity: Catch format errors before saving to your database.
Form Validation: Block submissions that don’t follow the expected SSN structure.
Use our JavaScript Regex Tester to experiment with variations or build custom patterns.
How to Validate SSNs in C#
If you’re working with .NET or C#, you can also use regular expressions to enforce correct SSN formatting and weed out common placeholder or invalid numbers. Here’s how you can implement a robust SSN validator in C#:
using System.Text.RegularExpressions; public static bool IsValidSSN(string ssn) { // This regex: // - Prevents area numbers 666, 000, or anything starting with 9 // - Ensures group (middle) isn’t 00, and serial (last four) isn’t 0000 var pattern = @"^(?!6660009\d{2})\d{3}-(?!00)\d{2}-(?!0{4})\d{4}$"; return Regex.IsMatch(ssn, pattern
Example usage:
var testSSNs = new[] { "856-45-6789", "000-45-6789", "856-452-6789", "856-45-0000" }; foreach (var s in testSSNs) { Console.WriteLine(IsValidSSN(s)); // Prints True or False
"856-45-6789"
→ Valid (True)"000-45-6789"
→ Invalid (area cannot be 000)"856-452-6789"
→ Invalid (bad format)"856-45-0000"
→ Invalid (serial cannot be 0000)
This approach lets you safeguard your application from the most common SSN input mistakes and helps keep your identity data cleaner from the start.
SSN Validation in C++ Using Regex
If you’re working in C++ and need to ensure Social Security Numbers are correctly formatted, you can easily incorporate SSN regex validation right into your codebase.
Here’s a practical approach:
Include the Required Libraries:
Make sure you have the<regex>
and<string>
headers available.Write the Validation Function:
Create a function that receives the SSN string and returns whether it matches the standard pattern.
#include #include #include // Checks if SSN matches the standard pattern bool isValidSSN(const std::string& ssn) { // Prevents invalid area, group, and serial numbers std::regex ssnPattern(R"(^(?!6660009\d{2})\d{3}-(?!00)\d{2}-(?!0{4})\d{4}$)"); return std::regex_match(ssn, ssnPattern); }
Sample Usage:
int main() { std::cout << std::boolalpha; std::cout << isValidSSN("856-45-6789") << std::endl; // true std::cout << isValidSSN("000-45-6789") << std::endl; // false std::cout << isValidSSN("856-452-6789") << std::endl; // false std::cout << isValidSSN("856-45-0000") << std::endl; // false return 0; }
How it works:
The pattern rejects SSNs starting with 666, 000, or any 9XX series.
It blocks group numbers like “00” and serial numbers like “0000”—both invalid.
This setup lets you catch mistyped or clearly invalid SSNs before they reach your application’s sensitive workflows.
Try adapting the regex for your business rules, or extend it for batch validation in larger datasets.
What Does the i
Modifier Do in SSN Regex?
When crafting regular expressions to validate Social Security Numbers, you might encounter the i
modifier at the end of a regex pattern—for example, /^[\dX]{3}-?[\dX]{2}-?[\dX]{4}$/i
. But what does this actually mean for your SSN validation?
The i
flag makes your pattern case-insensitive. In the context of SSNs, you might want to allow for special cases where an "X" can appear (such as in masked or placeholder SSNs). With the i
modifier, your regex would match both uppercase "X" and lowercase "x" in any part of the SSN:
Without
i
: Only matches uppercase "X" (e.g.,123-45-67X9
)With
i
: Matches both "X" and "x" (e.g.,123-45-67x9
or123-xx-xxxx
)
Use the i
modifier if you expect or want to accept either case, especially when handling data from different sources where the letter case might vary. This ensures your validation remains flexible without missing legitimate values.
A note on accuracy:
If you’ve ever browsed the “Valid SSNs” section on Wikipedia, you’ll know that validating Social Security Numbers (SSNs) with a regex is a bit more nuanced than it first appears. For example, a slightly more accurate regex pattern would be:
^(?!(0006669))\d{3}-(?!00)\d{2}-(?!0000)\d{4}$
This pattern improves on the basics by making sure that:
The first group isn’t “000”, “666”, or any number starting with “9”
The second group isn’t “00”
The last group isn’t “0000”
Still, even a more robust regex like this only weeds out obviously invalid formats—it can’t guarantee the number is officially assigned to anyone.
Format flexibility:
Depending on your needs, you might want to accept placeholders or optional dashes, like so:
/^(\d{3}-?\d{2}-?\d{4})(xxx-xx-xxxx)$/i
This allows for “xxx-xx-xxxx” or variations without dashes, which can be useful in certain testing or demonstration scenarios.
Bottom line:
Regex is great for filtering out the impossible, not for confirming the real. Always consult official documentation or validation services if you need to verify actual SSNs.
Pro Tips
Use .test() for fast checks in live form validation.
Avoid storing SSNs as plain text. Use the Base64 Encoder to obfuscate values before transmission.
For added security, combine regex validation with server-side checks and encryption.
Regularly test your regex with mock data using our Random String Generator or Token Generator.
Use the CSV to JSON Converter if you’re batch-validating SSNs from user-uploaded files.
Combine with These Tools
JavaScript Regex Tester – Test any regex patterns live.
Base64 Encoder – Encode sensitive strings before sending them over the web.
Token Generator – Generate secure tokens with your regex rules.
CSV to JSON Converter – Handle large imports of SSNs for validation and storage.
Frequently asked questions
Discover, Test, and Secure your APIs — 10x Faster.

Product
All Rights Reserved.
Copyright © 2025 Qodex
Discover, Test, and Secure your APIs — 10x Faster.

Product
All Rights Reserved.
Copyright © 2025 Qodex
SSN Regex Javascript Validator
Search...
⌘K
SSN Regex Javascript Validator
Search...
⌘K


SSN Regex Javascript Validator
SSN Regex Javascript Validator
Easily validate U.S. Social Security Numbers using our JavaScript Regex Tester. This tool ensures your input follows the standard XXX-XX-XXXX format. Whether you’re building secure onboarding flows or cleaning form data, pair it with our Base64 Encoder to protect sensitive info, or convert bulk files using the CSV to JSON Converter. Fast, accurate, and perfect for developers handling identity data.
[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 Javascript Validator - Documentation
What is an SSN Regex?
In the U.S., a Social Security Number (SSN) is a 9-digit number formatted as XXX-XX-XXXX. Validating this format is crucial in applications where identity verification or data entry accuracy is required.
A regular expression (regex) helps ensure the format is correct before any sensitive operations are performed.
Common SSN Regex Pattern
/^\d{3}-\d{2}-\d{4}$/
What This Pattern Does:
^\d{3}
: Start with exactly 3 digits-
: A hyphen\d{2}
: Followed by 2 digits-
: Another hyphen\d{4}$
: Ends with 4 digits
Valid SSN: 123-45-6789
Invalid SSN: 12-3456-789 or 123456789
A More Accurate SSN Regex
While the above pattern matches the standard SSN format, it doesn't catch all invalid possibilities. Certain combinations—like area numbers starting with 000, 666, or 9, or groups like 00 or 0000—aren't valid for real Social Security Numbers.
If you need a stricter check, consider this pattern:
^(?!(0006669))\d{3}-(?!00)\d{2}-(?!0000)\d{4}$
What’s Improved Here:
: Ensures the area number (the first three digits) is not 000, 666, or any number starting with 9.
: The group number (middle two digits) can’t be 00.
: The serial number (last four digits) can’t be 0000.
This extra layer helps weed out obviously invalid SSNs while still matching the correct format.
Example of valid SSN: 123-45-6789
Examples of invalid SSNs: 000-12-3456, 666-12-3456, 900-12-3456, 123-00-4567, 123-45-0000
Use the stricter pattern if you want to more closely mirror real-world SSN rules, but remember: even the best regex can't guarantee a number is actually issued to a real person.
A More Flexible Pattern for Custom Formats
If you’d like a regex that matches any groupings of non-hyphen characters following the familiar 3-2-4 split (but without requiring digits), you can tweak the pattern like so:
^[^-]{3}-?[^-]{2}-?[^-]
How This Pattern Works:
^[^-]{3}
: Start with exactly 3 characters that aren’t hyphens-?
: An optional hyphen[^-]{2}
: Next, 2 non-hyphen characters-?
: Another optional hyphen[^-]{4}$
: Finally, 4 non-hyphen characters
This is handy if you’re dealing with codes or IDs—such as ABC-DE-1234
or XyZ12aBcd
—that aren’t strictly numeric but still fit the 3-2-4 structure (with or without hyphens).
Examples matched:
ABC-DE-1234
xyz12abcd
B2C-D1-42k7
Examples not matched:
AB-DE-1234
(only 2 characters at the start)ABC--DE-1234
(contains double hyphens)A-BC-DE-1234
(incorrect grouping)
Feel free to adjust the numbers if your format varies!
Matching Both Numeric and Masked SSN Formats
If you want your regex to accept both standard numeric SSNs and those that use 'X' characters for masking (like XXX-XX-XXXX
), you'll just need to expand your pattern a bit.
Updated Regex Pattern
^(\d{3}-\d{2}-\d{4}[Xx]{3}-[Xx]{2}-[Xx]
What This Updated Pattern Does:
\d{3}-\d{2}-\d{4}
: Matches three digits, a hyphen, two digits, a hyphen, and four digits—just like before.[Xx]{3}-[Xx]{2}-[Xx]{4}
: Matches three Xs (upper or lowercase), a hyphen, two Xs, a hyphen, and four Xs.The pipe (``) lets you match either the numeric or masked version, but not a mix of both.
The
^
and$
match the start and end of the string to ensure the full SSN is validated.
Examples
Valid Numeric SSN: 123-45-6789
Valid Masked SSN: XXX-XX-XXXX or xxx-xx-xxxx
Invalid Mixed: 123-XX-6789
With this, you can confidently accept either the real SSN or the masked placeholder—no more watching for sneaky combinations!
Strict Pattern: Only Allowing 123-45-6789 or XXX-XX-XXXX
If you need a regex that matches only the specific SSNs 123-45-6789
or XXX-XX-XXXX
, here's what you need:
^
and$
ensure the pattern matches the entire string from start to finish.The pipe (``) acts as an "or," so it allows either
123-45-6789
orXXX-XX-XXXX
—nothing else.
Any input besides those two exact formats will be rejected.
Combining Multiple SSN Formats with Alternation
Suppose you need to accept both standard SSNs (numbers only) and placeholder formats (like all X's) in your regex. This is where alternation comes in handy. Alternation allows your regex to match either one pattern or another using the pipe character (``).
For example, let's say you want to allow:
Standard numeric SSNs:
123-45-6789
Placeholder SSNs:
XXX-XX-XXXX
You can combine them like this:
What this does:
The `` symbol means "or," so the regex will match if the input fits either the numeric pattern or the all-X pattern.
The parentheses group the alternatives, ensuring the regex matches the structure of either option from start to finish.
You can further adapt this pattern to allow flexibility, such as matching lowercase x with [Xx]
:
/^(\d{3}-\d{2}-\d{4}[Xx]{3}-[Xx]{2}-[Xx]
This way, entries like xxx-xx-xxxx
are also accepted. Use the i
flag (for case-insensitive matching) if your regex flavor supports it—making life even simpler.
So, with a single, well-structured regex and a bit of alternation, you can seamlessly validate multiple SSN formats in one go.
Allowing All Digits or All Xs (But Not Mixed) in SSN Regex
Suppose you want your SSN input to accept either the standard all-digit version (123-45-6789
) or a masked version using just Xs (XXX-XX-XXXX
), but never a mixture of the two. Here’s how you can do it:
Regex Breakdown
To achieve this, you’ll use the `` (pipe) operator, which means "or," and group patterns for clarity:
The first pattern matches only digits in the SSN format:
^\d{3}-\d{2}-\d{4}$
The second pattern matches only Xs (case-insensitive), same format:
^[Xx]{3}-[Xx]{2}-[Xx]{4}$
Combine them like so:
/^(\d{3}-\d{2}-\d{4}[Xx]{3}-[Xx]{2}-[Xx]
Or, if your language supports it, you can use the case-insensitive flag (i
) so you only need [X]{3}-[X]{2}-[X]{4}
.
What Does This Do?
Digits-only allowed:
123-45-6789
Xs-only allowed:
XXX-XX-XXXX
(accepts both uppercase and lowercase X)No mixing: Patterns like
12X-4X-6789
will not match
This keeps input consistent and secure, especially for forms masking sensitive information.
Tip: To relax about hyphens (e.g., optional hyphens), replace -
with -?
in both alternatives.
With this approach, your form or validator strictly allows either genuine numeric SSNs or fully redacted ones—never a blended masquerade.
SSN Validation: Beyond the Basics
While matching the XXX-XX-XXXX format is a good start, a truly valid SSN must also meet a few more specific criteria:
9 Digits Only: The SSN must have exactly 9 digits, no more, no less.
Hyphenated in 3 Parts: The number is always split into three parts by hyphens: the first part (3 digits), the second part (2 digits), and the third part (4 digits).
First Part Restrictions: The first three digits cannot be , , or any number in the range .
Second Part Range: The middle two digits must be between and — is not valid.
Third Part Range: The last four digits must be between and — is not valid.
For example, while is valid, numbers like , , or would fail these checks.
By combining regex formatting and these additional rules, you can more confidently validate SSNs and filter out invalid or potentially fraudulent entries.
Performance Considerations
When it comes to validating an SSN with this regex pattern, the process examines each character in the input string once, making the time complexity linear—O(N), where N is the number of characters. The space requirements are minimal, as the regex engine does not need extra memory proportional to the size of the input. In short, you get efficient validation both in speed and memory use.
How to Validate SSNs in JavaScript
Here’s a complete JavaScript code example:
function isValidSSN(ssn) { const ssnRegex = /^\d{3}-\d{2}-\d{4}$/; return ssnRegex.test(ssn); } // Example usage: console.log(isValidSSN("123-45-6789")); // true console.log(isValidSSN("123456789")); // false
How to Validate SSNs in Python
Need to ensure SSNs fit the proper mold in your Python application? Let's walk through an easy approach using regular expressions—great for backend checks or data migrations.
Here's a typical function to validate SSN format in Python:
import re def is_valid_ssn(ssn): pattern = r"^(?!6660009\d{2})\d{3}-(?!00)\d{2}-(?!0000)\d{4}$" return bool(re.match(pattern, ssn))
How it works:
^(?!6660009\d{2})\d{3}
: The SSN can't start with 666, 000, or any number between 900-999.-(?!00)\d{2}
: The middle two digits can't be 00.-(?!0000)\d{4}$
: The last four digits can't be 0000.
Examples:
print(is_valid_ssn("856-45-6789")) # True – valid SSN print(is_valid_ssn("000-45-6789")) # False – invalid, leading block not allowed print(is_valid_ssn("856-452-6789")) # False – wrong format print(is_valid_ssn("856-45-0000")) # False – trailing block not allowed
This approach quickly weeds out most SSN format issues and can easily be adapted for batch processing or user input validation. For extra protection, pair this with secure storage solutions—never keep SSNs in plain sight!
How to Validate SSNs Using Regex in Java
Just like in JavaScript, you can also use a regular expression in Java to check Social Security Number formats efficiently—and even add a bit more rigor.
Here’s what a typical validation function looks like in Java:
import java.util.regex.Pattern; public class SSNValidator { // Pattern blocks obviously invalid ranges (000, 666, 900–999 in the first group; 00 in the middle; 0000 at the end) private static final Pattern SSN_REGEX = Pattern.compile( "^(?!6660009\\d{2})\\d{3}-(?!00)\\d{2}-(?!0{4})\\d{4}$" ); public static boolean isValidSSN(String ssn) { if (ssn == null) return false; return SSN_REGEX.matcher(ssn).matches(); } // Example usage public static void main(String[] args) { 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 } }
How it Works:
The regex prevents common invalid SSNs, such as those starting with 666, 000, or any 900–999 series, as well as entries with all zeros in the middle or end.
The function returns
true
only if the input matches both SSN format and these stricter rules.As always, make sure to check for
null
before attempting the match to avoid exceptions.
This approach provides an extra layer of safety, catching not only mistyped formats but also values explicitly blocked by the Social Security Administration.
Where Can SSN Regex Be Used?
User Onboarding: Ensure users enter valid SSNs in financial or HR applications.
Database Integrity: Catch format errors before saving to your database.
Form Validation: Block submissions that don’t follow the expected SSN structure.
Use our JavaScript Regex Tester to experiment with variations or build custom patterns.
How to Validate SSNs in C#
If you’re working with .NET or C#, you can also use regular expressions to enforce correct SSN formatting and weed out common placeholder or invalid numbers. Here’s how you can implement a robust SSN validator in C#:
using System.Text.RegularExpressions; public static bool IsValidSSN(string ssn) { // This regex: // - Prevents area numbers 666, 000, or anything starting with 9 // - Ensures group (middle) isn’t 00, and serial (last four) isn’t 0000 var pattern = @"^(?!6660009\d{2})\d{3}-(?!00)\d{2}-(?!0{4})\d{4}$"; return Regex.IsMatch(ssn, pattern
Example usage:
var testSSNs = new[] { "856-45-6789", "000-45-6789", "856-452-6789", "856-45-0000" }; foreach (var s in testSSNs) { Console.WriteLine(IsValidSSN(s)); // Prints True or False
"856-45-6789"
→ Valid (True)"000-45-6789"
→ Invalid (area cannot be 000)"856-452-6789"
→ Invalid (bad format)"856-45-0000"
→ Invalid (serial cannot be 0000)
This approach lets you safeguard your application from the most common SSN input mistakes and helps keep your identity data cleaner from the start.
SSN Validation in C++ Using Regex
If you’re working in C++ and need to ensure Social Security Numbers are correctly formatted, you can easily incorporate SSN regex validation right into your codebase.
Here’s a practical approach:
Include the Required Libraries:
Make sure you have the<regex>
and<string>
headers available.Write the Validation Function:
Create a function that receives the SSN string and returns whether it matches the standard pattern.
#include #include #include // Checks if SSN matches the standard pattern bool isValidSSN(const std::string& ssn) { // Prevents invalid area, group, and serial numbers std::regex ssnPattern(R"(^(?!6660009\d{2})\d{3}-(?!00)\d{2}-(?!0{4})\d{4}$)"); return std::regex_match(ssn, ssnPattern); }
Sample Usage:
int main() { std::cout << std::boolalpha; std::cout << isValidSSN("856-45-6789") << std::endl; // true std::cout << isValidSSN("000-45-6789") << std::endl; // false std::cout << isValidSSN("856-452-6789") << std::endl; // false std::cout << isValidSSN("856-45-0000") << std::endl; // false return 0; }
How it works:
The pattern rejects SSNs starting with 666, 000, or any 9XX series.
It blocks group numbers like “00” and serial numbers like “0000”—both invalid.
This setup lets you catch mistyped or clearly invalid SSNs before they reach your application’s sensitive workflows.
Try adapting the regex for your business rules, or extend it for batch validation in larger datasets.
What Does the i
Modifier Do in SSN Regex?
When crafting regular expressions to validate Social Security Numbers, you might encounter the i
modifier at the end of a regex pattern—for example, /^[\dX]{3}-?[\dX]{2}-?[\dX]{4}$/i
. But what does this actually mean for your SSN validation?
The i
flag makes your pattern case-insensitive. In the context of SSNs, you might want to allow for special cases where an "X" can appear (such as in masked or placeholder SSNs). With the i
modifier, your regex would match both uppercase "X" and lowercase "x" in any part of the SSN:
Without
i
: Only matches uppercase "X" (e.g.,123-45-67X9
)With
i
: Matches both "X" and "x" (e.g.,123-45-67x9
or123-xx-xxxx
)
Use the i
modifier if you expect or want to accept either case, especially when handling data from different sources where the letter case might vary. This ensures your validation remains flexible without missing legitimate values.
A note on accuracy:
If you’ve ever browsed the “Valid SSNs” section on Wikipedia, you’ll know that validating Social Security Numbers (SSNs) with a regex is a bit more nuanced than it first appears. For example, a slightly more accurate regex pattern would be:
^(?!(0006669))\d{3}-(?!00)\d{2}-(?!0000)\d{4}$
This pattern improves on the basics by making sure that:
The first group isn’t “000”, “666”, or any number starting with “9”
The second group isn’t “00”
The last group isn’t “0000”
Still, even a more robust regex like this only weeds out obviously invalid formats—it can’t guarantee the number is officially assigned to anyone.
Format flexibility:
Depending on your needs, you might want to accept placeholders or optional dashes, like so:
/^(\d{3}-?\d{2}-?\d{4})(xxx-xx-xxxx)$/i
This allows for “xxx-xx-xxxx” or variations without dashes, which can be useful in certain testing or demonstration scenarios.
Bottom line:
Regex is great for filtering out the impossible, not for confirming the real. Always consult official documentation or validation services if you need to verify actual SSNs.
Pro Tips
Use .test() for fast checks in live form validation.
Avoid storing SSNs as plain text. Use the Base64 Encoder to obfuscate values before transmission.
For added security, combine regex validation with server-side checks and encryption.
Regularly test your regex with mock data using our Random String Generator or Token Generator.
Use the CSV to JSON Converter if you’re batch-validating SSNs from user-uploaded files.
Combine with These Tools
JavaScript Regex Tester – Test any regex patterns live.
Base64 Encoder – Encode sensitive strings before sending them over the web.
Token Generator – Generate secure tokens with your regex rules.
CSV to JSON Converter – Handle large imports of SSNs for validation and storage.
Frequently asked questions
Discover, Test, and Secure your APIs — 10x Faster.

Product
All Rights Reserved.
Copyright © 2025 Qodex
Discover, Test, and Secure your APIs — 10x Faster.

Product
All Rights Reserved.
Copyright © 2025 Qodex