Search code examples
pythonpasswordsfastapi

i want to validate password for user input in fastapi python


i need a password validation in fastapi python, in this when user signup and create a password and passowrd are too sort not capital letter, special character etc. than fastapi give validation error

i make a password validation code in python but i don't know how to use in fastapi

def validate_password(s):
    l, u, p, d = 0, 0, 0, 0
    capitalalphabets="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    smallalphabets="abcdefghijklmnopqrstuvwxyz"
    specialchar=""" ~`!@#$%^&*()_-+={[}]|\:;"'<,>.?/ """
    digits="0123456789"
    if (len(s) >= 8):
        for i in s:
    
            # counting lowercase alphabets
            if (i in smallalphabets):
                l+=1           
    
            # counting uppercase alphabets
            if (i in capitalalphabets):
                u+=1           
    
            # counting digits
            if (i in digits):
                d+=1           
    
            # counting the mentioned special characters
            if(i in specialchar):
                p+=1       
    if (l>=1 and u>=1 and p>=1 and d>=1 and l+p+u+d==len(s)):
        print("Valid Password")
    else:
        print("Invalid Password")

s = input("Enter the password: ") 
validate_password(s)

Solution

  • You can import validator from Pydantic and fill it by your field name of your schema (in this case "password").

    Usage in your schema file:

    from pydantic import BaseModel, validator
    
    class User(BaseModel):
        password: str
    
        @validator("password")
        def validate_password(cls, password, **kwargs):
            # Put your validations here
            return password
    

    For this problem, a better solution is using regex for password validation and using regex in your Pydantic schema.

    Example of strong password regex validation:

    from pydantic import BaseModel, Field
    
    password_regex = "((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[\W]).{8,64})"
    
    
    class User(BaseModel):
        password: str = Field(..., regex=password_regex)