How to create multiple constrained types in Pydantic

Viewed 2162

I am trying to put a constraint on a secret string. If I could, for instance, I would like something like this:

from pydantic import constr, SecretStr

class SimpleModel(BaseModel):
    password: (SecretStr, constr(min_length=8, max_length=32))

And if it is possible to do something that accomplishes this, my next question will be: Can I also add a constraint that a non-word character is needed? I can do regex checks on my own, but I am trying to adopt pydantic more fully.

1 Answers

This is not possible with SecretStr at the moment. Until a PR is submitted you can used validators to achieve the same behaviour:

import re
from pydantic import AnyStrMinLengthError, AnyStrMaxLengthError, BaseModel, SecretStr, StrRegexError, validator

class SimpleModel(BaseModel):
    password: SecretStr

    @validator('password')
    def has_min_length(cls, v):
        min_length = 8
        if len(v.get_secret_value()) < min_length:
            raise AnyStrMinLengthError(limit_value=min_length)
        return v

    @validator('password')
    def has_max_length(cls, v):
        max_length = 32
        if len(v.get_secret_value()) > max_length:
            raise AnyStrMaxLengthError(limit_value=max_length)
        return v

    @validator('password')
    def matches_regex(cls, v):
        regex = r'.*\W'
        if not re.match(regex, v.get_secret_value()):
            raise StrRegexError(pattern=regex)
        return v
Related