-
Hello, I would like a type for my models that validates strings and makes sure they are not empty and do not contain any NUL ( I'd like something like this if possible: class MyModel(BaseModel)
value: NonEmptyString # Checks for empty and NUL characters |
Beta Was this translation helpful? Give feedback.
Answered by
ybressler
Apr 25, 2024
Replies: 1 comment
-
You can use a constrained string: from pydantic import constr
NonEmptyString = constr(strip_whitespace=True, min_length=1, pattern='[^\0]+') Alternatively, if you want more control, you can use an annotated validator: from pydantic.functional_validators import AfterValidator
def do_something(v: str) -> str:
if "something" in v:
raise ValueError()
return v
NonEmptyString = Annotated[
constr(strip_whitespace=True, min_length=1, pattern='[^\0]+'),
AfterValidator(do_something)
] |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
Spaxterr
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can use a constrained string:
Alternatively, if you want more control, you can use an annotated validator: