'SSN validator - Differentiating digits and chars

this is my first time asking here in stack. I have a question regarding this code:

ssn = str(input("Enter your ssn:"))

if (len(ssn) == 11 and ssn[3] == '-' and ssn[6] == '-'):
  print(ssn + " is a valid social security number.")
else:
  print(ssn + " is not a valid social security number.")

So the thing is, i thought this code was good if I typed in the normal format like 123-45-6789 and it would give me the correct print statement. However, i also noticed that if i typed in ddd-dd-dddd, it also gives me the logically correct print statement but i only want to work for digits.

Thank you so much in advance for helping me out, I'm currently a student and relatively young in the field of programming. Any outputs would be appreciated.



Solution 1:[1]

There is a function in python called isdigit() which checks to see if the string entered is a digit. We can use it along with taking a subsset of your string we can check if the other parts are digits.

ssn = str(input("Enter your ssn:"))

if (len(ssn) == 11 and ssn[0:3].isdigit() and ssn[3] == '-' and ssn[4:6].isdigit() and ssn[6] == '-' and ssn[7:].isdigit()):
  print(ssn + " is a valid social security number.")
else:
  print(ssn + " is not a valid social security number.")

Since you mentioned that you were new to programming, just to clarify a bit, ssn[x:y] takes characters from index x upto (but not including) index y and allows you to treat it as a separate string.

Solution 2:[2]

This is a simple regular expression for validating ssn number.

const validSsn = (value: string) =>
  value && /^(?!(000|666|9))(\d{3}-?(?!(00))\d{2}-?(?!(0000))\d{4})$/.test(value)
  ? true
  : false

Above code taken from SSNValidator.org

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Karan Shishoo
Solution 2 NIkhil Desk