Home > Software design >  Function that validates a new password
Function that validates a new password

Time:04-25

I want to create a program which calls a function that asks for a password, then asks again to confirm it. if the passwords don't match or the rules are not fulfilled, prompt again. This function should include a function that checks whether a password is valid based on the next rules:

  1. The password must be as least 8 characters long
  2. The password must have at least one uppercase and one lowercase letter
  3. The password must have at least one digit

Note: it is not OOP, and I don't think this code requires a library (its fine if it needs but I would prefer no library)

CodePudding user response:

The most difficult part of your problem is to check whether a password passes all the rules, to do that you can try this function:

def password_check(passwd):
    if len(passwd) < 8:
        return False
    if not any(char.isdigit() for char in passwd):
        print('Password should have at least one number')
        return False
    if not any(char.isupper() for char in passwd):
        print('Password should have at least one uppercase character')
        return False
    if not any(char.islower() for char in passwd):
        print('Password should have at least one lowercase character')
        return False
    return True

After having implemented the function, if you need to get input from user and confirm the password, you can use input() function:

inputPass = input("Insert a password: ")
while not password_check(inputPass):
    inputPass = input("Insert a password: ")
inputPass2 = input("Confirm the password: ")
while inputPass2!=inputPass:
    inputPass2 = input("Confirm the password: ")

CodePudding user response:

def validate(password):
    if len(password) < 8:
        return False
    if not any(char.isdigit() for char in password):
        return False
    if not any(char.isupper() for char in password):
        return False
    if not any(char.islower() for char in password):
        return False
    return True
  • Related