Archirk
Archirk

Reputation: 639

How to use validators in Strict Types of Pydantic like StrictStr?

Currently I have schema with field "name". I use constr to specify it

from pydantic import BaseModel, constr

class MySchema(BaseModel):
    name: constr(strict=True, min_length=1, max_length=50)

I want to use pydantic StrictStr type like this:

from pydantic import BaseModel, StrictStr, Field

class MySchema(BaseModel):
    name: StrictStr = Field(min_length=1, max_length=50)

But it raises error:

E   ValueError: On field "name" the following field constraints are set but not enforced: max_length, min_length.
E   For more details see https://pydantic-docs.helpmanual.io/usage/schema/#unenforced-field-constraints

In docs, as i understand, it advices to use use raw attribute name like maxLength isntead of max_length(like exclusiveMaximum for int) but this constraints are not enforced so validations are not applied.

My question is: How I can use StrictStr type for name field and apply native validations like min_length, max_length?

Upvotes: 2

Views: 5124

Answers (1)

Simon Hawe
Simon Hawe

Reputation: 4539

You have multiple options here, either you create a new type based on StrictString, or you inherit from StrictString or you use constr with strict set to True. Creating a type as done below does the same as inheriting from StrictString, just a different syntax if you want. That should all give you the necessary type validations. In code, that would read like

MyStrictStr1 = type('MyStrictStr', (StrictStr,), {"min_length":1, "max_length":5})


class MyStrictStr2(StrictStr):
    min_length = 1
    max_length = 5

MyStrictStr3 = constr(min_length=1, max_length=5, strict=True)

Upvotes: 2

Related Questions