Can someone provide me a regex for SSN that matches either
123-45-6789
OR
XXX-XX-XXXX
I currently have ^\d{3}-?\d{2}-?\d{4}$
which matches the first expression, but I need to add the second expression to it as an alternative.
Thanks!
To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).
The Regex number range include matching 0 to 9, 1 to 9, 0 to 10, 1 to 10, 1 to 12, 1 to 16 and 1-31, 1-32, 0-99, 0-100, 1-100,1-127, 0-255, 0-999, 1-999, 1-1000 and 1-9999.
The Validation (Regex) property helps you define a set of validation options for a given field. In general, this field property is used to perform validation checks (format, length, etc.) on the value that the user enters in a field. If the user enters a value that does not pass these checks, it will throw an error.
To strictly answer you question:
^(123-45-6789|XXX-XX-XXXX)$
should work. ;-)
If you read the section "Valid SSNs" on Wikipedia`s SSN article then it becomes clear that a regex for SSN validation is a bit more complicated.
Accordingly a little bit more accurate pure SSN regex would look like this:
^(?!(000|666|9))\d{3}-(?!00)\d{2}-(?!0000)\d{4}$
(^\d{3}-?\d{2}-?\d{4}$|^XXX-XX-XXXX$)
should do it.
---- EDIT ----
As Joel points out you could also do ^(\d{3}-?\d{2}-?\d{4}|XXX-XX-XXXX)$
which is a little neater.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With