Basic SSN Regex Validator
“Regex”, short for “regular expression” is a crucial tool for any developer. Regex is defined as a sequence of characters that define a search pattern, especially useful for string-searching algorithms. In this blog, I will cover a basic instance that has helped me in my understanding. For more documentation, I personally use the following link (Javascript):
https://www.w3schools.com/jsref/jsref_obj_regexp.asp
For our example, we will look at creating a Social Security Number validator in React Native. For this, the following must be met:
1. 3 digits, followed by 2 digits, followed by 4 digits, separated by dashes.
2. only numbers
The code block for the SSN regex is:
To break this down:
“ /^\d{3}” means matches any string with 3 digits
“-?” means contains 0 or 1 occurrence of “-”
“\d{2} followed by 2 digits
“-?” followed by 0 or 1 occurrence of “-”
\d{4}$/ means ends with 4 digits.
Once we have to regex set up, we can call regex.test(valueToTest) which will return our value.
Here is the full SSN Validator App, hooks and React native: