| 61 | } |
| 62 | |
| 63 | function formatSSN(value: string) { |
| 64 | // if input value is falsy eg if the user deletes the input, then just return |
| 65 | if (!value) return value; |
| 66 | |
| 67 | // clean the input for any non-digit values |
| 68 | const ssn = value.replace(/[^\d]/g, ''); |
| 69 | |
| 70 | // ssnLength is used to know when to apply our formatting for the ssn |
| 71 | const ssnLength = ssn.length; |
| 72 | |
| 73 | // we need to return the value with no formatting if its less then four digits |
| 74 | if (ssnLength < 4) return ssn; |
| 75 | |
| 76 | // if ssnLength is greater than 4 and less the 6 we start to return |
| 77 | // the formatted number |
| 78 | if (ssnLength < 6) { |
| 79 | return `${ssn.slice(0, 3)}-${ssn.slice(3)}`; |
| 80 | } |
| 81 | |
| 82 | // finally, if the ssnLength is greater then 6, we add the last |
| 83 | // bit of formatting and return it. |
| 84 | return `${ssn.slice(0, 3)}-${ssn.slice(3, 5)}-${ssn.slice(5, 9)}`; |
| 85 | } |