Question: How can I verify that the format of a Mexican SSN is valid?
What is the NSS? The Social Security Number (NSS) is the worker's social identity. It is issued by the IMSS and is made up of 11 digits.
Context: I want to validate that a SSN could be valid. I'm not interested in seeing if it actually exists. I am currently validating that they are 11 digits:
/^\d{11}$/
but now I'm interested to see if it can be more strictly validated.
SSN format
The Social Security Number is constituted by:
IMSS Subdelegation codes are listed in the NSS Integration Manual ? . While some (few) numbers are not valid, they might be in the future, so we can't validate for that field. Also, in the special cases when there is no record of the date of birth, the code is used
97
.When you have a date of birth, logically it must be less than the year of discharge of the worker.
The check digit is assigned using the Luhn algorithm , which will allow us to validate the SSN.
Regular phrase
Only 11 digits will be validated, but we will use the expression to capture the first 3 fields separately:
Full Validation
I publish the code in JavaScript to be able to execute it here, but it is very easy to port it to any other language.
Description
After validating that there are 11 digits and having separated the first 3 fields, it is compared that the year of birth is prior to the year of registration. Since we only have the last digits of the year, 100 is added to the number if it is less than the current year (so '05 will be greater than '99 for example).
However, the main validation is by the Luhn algorithm, which consists of taking the digits in odd positions, and the digits in even positions multiplied by 2. All the digits are added (if any of these were greater than or equal to 10, take the sum of each digit).
A SSN is valid if the last digit of that sum equals
0
.