python

Validate password with and without regex in Python

When you are signing up a user, you want to add some validations like uppercase letters, numbers, special characters to your password. Below are some code examples in python that can be helpful to validate your password string.

#without using regex
def validate_password(password):
  special_chars =['$', '!', '@', '#', '%', '&']
  validated = True
  msg = ''

  if len(password) < 8:
    msg = 'Password length must be at least 8'
    validated = False
    
  elif len(password) > 18:
    msg = 'Password length must not be greater than 18'
    validated = False
    
  elif not any(char.isdigit() for char in password):
    msg = 'Password should have at least one number'
    validated = False

  elif not any(char.isupper() for char in password):
    msg = 'Password should have at least one uppercase letter'
    validated = False

  elif not any(char.islower() for char in password):
    msg = 'Password should have at least one lowercase letter'
    validated = False
        
  elif not any(char in special_chars for char in password):
    msg = 'Password should have at least one special character'
    validated = False
    
  return { 'is_valid': validated, 'message': msg }

print(validate_password('Hellowewew1@'))
Output
{'is_valid': True, 'message': ''}
import re

def password_is_valid(password):
  pwd_regex = '^(?=\S{8,18}$)(?=.*?\d)(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[^A-Za-z\s0-9])'
  compiled_regex = re.compile(pwd_regex)
  
  if (re.search(compiled_regex, password)):
    return True
  else:
    return False
  
if (password_is_valid('Devsheet43@')):
  print('Password is valid')
else:
  print('Password is invalid')
You can use regex also to validate your password string. In the above code, we have validated our password if it passes the below criteria

1. Password length must be greater than 8 and less than 18.
2. Password includes at least one Uppercase character.
3. Password includes at least one special character.
4. Password must contain at least one number.
import re

def validate_password(password):
  if len(password) < 8:
    print("Password length must be greater than 8")
  elif len(password) > 18:
    print("Password length must be less than 18")
  elif re.search('[0-9]',password) is None:
    print("Password must contain a number")
  elif re.search('[A-Z]',password) is None: 
    print("Password must contain a capital letter")
  else:
    print("Password is valid")

validate_password("Devsheet123")
You can validate a password using regex for each validation that contains the specific message of validation.
Was this helpful?