pythonpydantic

How to do with Pydantic regex validation?


I'm trying to write a validator with usage of Pydantic for following strings (examples): 1.1.0, 3.5.6, 1.1.2, etc..

I'm failing with following syntax:

install_component_version: constr(regex=r"^[0-9]+.[0-9]+.[0-9]$")
install_component_version: constr(regex=r"^([0-9])+.([0-9])+.([0-9])$")
install_component_version: constr(regex=r"^([0-9])\.([0-9])\.([0-9])$")

Can anyone help me out what regex syntax should look like?


Solution

  • The error you are facing is due to type annotation.

    As per https://github.com/pydantic/pydantic/issues/156 this is not yet fixed, you can try using pydantic.Field and then pass the regex argument there like so

    install_component_version: str = Field(regex=r"^[0-9]+.[0-9]+.[0-9]$")
    

    This way you get the regex validation and type checking.

    PS: This is not a 100% alternative to constr but if all you want is regex validation, the above alternative works and makes mypy happy.

    :warning: pydantic v2

    As mentioned in the comments, if using Pydantic V2, regex is replaced with pattern.

    install_component_version: str = Field(pattern=r"^[0-9]+.[0-9]+.[0-9]$")