<@ULVA73B9P> How do i add validator for validating...
# marvin-in-the-wild
k
@Marvin How do i add validator for validating the pydantic model in the workflow input parameters?
m
To add a validator for validating a Pydantic model in your Prefect workflow input parameters, you can use type hints with Pydantic models. When you define a flow in Prefect, type hints are automatically enforced by converting them to the relevant object types. Here's an example of how to do this:
Copy code
python
from prefect import flow
from pydantic import BaseModel, validator
from typing import Literal

# Define your Pydantic model
class Model(BaseModel):
    a: int
    b: float
    c: str

# Use the Pydantic model as a type hint in your flow
@flow
def model_validator_flow(model: Model):
    print(model)

# You can also use Pydantic validators for more complex validations
class ShirtOrder(BaseModel):
    size: Literal["small", "medium", "large", "xlarge"]
    color: Literal["red", "green", "black"]

    @validator("color")
    def validate_color(cls, value, values, **kwargs):
        if value == "green" and values["size"] == "small":
            raise ValueError(
                "Green is only in-stock for medium, large, and XL sizes."
            )
        return value

# Then you could use this model in a flow as well
@flow
def shirt_order_flow(order: ShirtOrder):
    print(order)
When you invoke your flow, the input parameters will be automatically validated against the Pydantic model. Incorrect types or failed custom validations will raise an error. Here are some links to the documentation sections that cover this topic: - Using Type Hints in Flows - Handling Custom Validation Ensure that you use Prefect 2.x syntax, as Prefect 1.x has different ways of handling these operations.
k
I have validator in my pydantic data model to check for two fields being mutually exclusive (one of them has to be set though), but it passed the validation when triggering the workflow on the UI 😞 The following is my validator for the class
Copy code
@validator("attr_1")
    def validate_mutually_exclusive(cls, v, values):
        if v is None and values.get("attr_2") is None:
            raise ValueError(
                "attr_1 and attr_2 are mutually exclusive. One of them must can be set."
            )
        return v