How can I validate US Social Security Number?

后端 未结 8 1463
鱼传尺愫
鱼传尺愫 2020-12-08 02:44

Anyone out there know how to improve this function? I\'m not worried about shortening the code, I\'m sure this could be done with better regex, I am more concerned about cor

8条回答
  •  离开以前
    2020-12-08 03:12

    I know this is an old question, but for the sake of others looking for answers, I figured I'd add a quick javascript function for checking that a given SSN is valid.

    function checkSSN() {
        var inputSSN = #YourInput#,
            ssnRegex = new RegExp("^(9[0-9][0-9]|666|000|078051120|219099999|123456789|123121234|321214321)|^([0-8][0-9][0-9]00)|^([0-8][0-9][0-9][0-9][0-9]000)$"),
            repeats = /^(.)\1+$/;
            
        //make sure we have 2 dashes in the input Social Security number
        if( inputSSN.match(/./g).length === 2) {
            //Once we have confirmed that there are the right number of dashes, remove them, and make sure that the resulting string is a number (you may or may not need this logic depending on the format of your input SSN.
            inputSSN = inputSSN.replace(/-/g, "");
    
            if(!isNaN(inputSSN)) {
                //Test the input SSN against our regex to ensure that it doesn't contain any disqualifying combinations.
                if(!ssnRegex.test(inputSSN)) {
                    //Make sure the input SSN isn't just a repeated number
                    if(!repeats.test(inputSSN)) {
                        //If it lands inside of this, we know it's a valid option for a social security number.
                    }
            }   
        }
    }
    

    For the ssnRegex logic:

    The first section handles if the SSN starts with a number 900-999, 666, 000, or one of the known disqualifying SSNs mentioned above.

    ^(9[0-9][0-9]|666|000|078051120|219099999|123456789|123121234|321214321)

    the second section ensures that the 2 digit portion isn't 00

    ^([0-8][0-9][0-9]00)

    The third section ensures that the last portion isn't 0000

    ^([0-8][0-9][0-9][0-9][0-9]0000)

    We additionally check to make sure they have inputted a number, and that they aren't just using a repeated number.

提交回复
热议问题