使用 pydantic 进行密码验证

问题描述 投票:0回答:1

为了避免使用 if else 循环,我执行了以下操作以在 pydantic 中添加密码验证

    @field_validator("password")
    def check_password(cls, value):
        # convert the password to a string if it is not already
        value = str(value)

        # Check that the password meets the criteria
        if len(value) < 8:
            raise ValueError("Password must have at least 8 characters")
       
        if not any(c.isupper() and c.islower() and c.isdigit() and c in string.punctuation for c in value):
            raise ValueError("Password must have at least one uppercase letter, one lowercase letter, and one digit")

        return value

但不幸的是,

if not any
条件无法正常工作,有人可以帮我修复它吗?

python python-3.x python-re pydantic
1个回答
0
投票

不存在同时为大写、小写、数字和标点符号的字符。

您需要:

if not any(c.isupper() for c in value) or \
   not any(c.islower() for c in value) or \
   not any(c.isdigit() for c in value) or \
   not any(c in punctionation for c in value): 
  ... handle bad password ...
© www.soinside.com 2019 - 2024. All rights reserved.