Skip to content

Type for not allowing NUL characters in strings #9316

Answered by ybressler
Spaxterr asked this question in Question
Discussion options

You must be logged in to vote

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)
]

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by Spaxterr
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
2 participants