Skip to content
Advertisement

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?

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement