Skip Validation of a Field Based on the Contents of Another #9208
-
This could be related to Discussion 4248. It's possible my desired behavior is outside the scope of Pydantic, but I'd like to skip validation for one field if the value of another matches a particular value. In the below example, if the value of Sorry if this question is a bit unclear or an answer already exists. I searched, but was unable to find a suitable solution. class Color(StrEnum):
BLUE = "U"
RED = "R"
class BorderColor(StrEnum):
BLACK = auto()
BORDERLESS = auto()
SILVER = auto()
class MyModel(BaseModel):
border_color: BorderColor | None = Field(
default=None,
description="Border color of this card.",
)
produced_colors: set[Color] | None = Field(
default=None,
description="Colors this card can produce.",
) |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
It's should be possible to achive it using from enum import StrEnum, auto
from typing import Any, Callable
from pydantic import BaseModel, Field, field_validator
from pydantic_core.core_schema import ValidationInfo
class Color(StrEnum):
BLUE = "U"
RED = "R"
class BorderColor(StrEnum):
BLACK = auto()
BORDERLESS = auto()
SILVER = auto()
class MyModel(BaseModel):
border_color: BorderColor | None = Field(
default=None,
description="Border color of this card.",
)
produced_colors: set[Color] | None = Field(
default=None,
description="Colors this card can produce.",
)
@field_validator("produced_colors", mode="wrap")
def _validate_produced_colors(cls, val: Any | None, next_: Callable[[Any], Any], ctx: ValidationInfo) -> Any:
if ctx.data.get("border_color") == BorderColor.SILVER:
return val
return next_(val)
model = MyModel(
border_color=BorderColor.SILVER,
produced_colors={Color.BLUE, Color.RED},
) |
Beta Was this translation helpful? Give feedback.
It's should be possible to achive it using
wrap
validator: