|
| 1 | +<!-- related-cli-options: --validators --> |
| 2 | + |
| 3 | +# Field Validators |
| 4 | + |
| 5 | +The `--validators` option allows you to add custom field validators to generated Pydantic v2 models. This enables you to inject validation logic into generated code without manually editing it. |
| 6 | + |
| 7 | +## Basic Usage |
| 8 | + |
| 9 | +```bash |
| 10 | +datamodel-codegen --input schema.json --output model.py \ |
| 11 | + --validators validators.json \ |
| 12 | + --output-model-type pydantic_v2.BaseModel |
| 13 | +``` |
| 14 | + |
| 15 | +## Validators File Format |
| 16 | + |
| 17 | +The validators file is a JSON file that maps model names to their validator definitions. |
| 18 | + |
| 19 | +### Structure |
| 20 | + |
| 21 | +```json |
| 22 | +{ |
| 23 | + "ModelName": { |
| 24 | + "validators": [ |
| 25 | + { |
| 26 | + "field": "field_name", |
| 27 | + "function": "module.path.to.validator_function", |
| 28 | + "mode": "after" |
| 29 | + } |
| 30 | + ] |
| 31 | + } |
| 32 | +} |
| 33 | +``` |
| 34 | + |
| 35 | +### Fields |
| 36 | + |
| 37 | +| Field | Description | Required | |
| 38 | +|-------|-------------|----------| |
| 39 | +| `field` | Single field name to validate | One of `field` or `fields` | |
| 40 | +| `fields` | List of field names (for multi-field validators) | One of `field` or `fields` | |
| 41 | +| `function` | Fully qualified path to the validator function | Yes | |
| 42 | +| `mode` | Validator mode: `before`, `after`, `wrap`, or `plain` | No (default: `after`) | |
| 43 | + |
| 44 | +## Validator Modes |
| 45 | + |
| 46 | +Pydantic v2 supports different validator modes, each with its own signature: |
| 47 | + |
| 48 | +### `before` / `after` Mode |
| 49 | + |
| 50 | +Standard validators that run before or after Pydantic's own validation: |
| 51 | + |
| 52 | +```python |
| 53 | +def validate_name(v: Any, info: ValidationInfo) -> Any: |
| 54 | + if not v: |
| 55 | + raise ValueError("Name cannot be empty") |
| 56 | + return v.strip() |
| 57 | +``` |
| 58 | + |
| 59 | +### `wrap` Mode |
| 60 | + |
| 61 | +Wrap validators receive a handler to call the next validator in the chain: |
| 62 | + |
| 63 | +```python |
| 64 | +from pydantic import ValidationInfo, ValidatorFunctionWrapHandler |
| 65 | + |
| 66 | +def wrap_validate_name( |
| 67 | + v: Any, |
| 68 | + handler: ValidatorFunctionWrapHandler, |
| 69 | + info: ValidationInfo |
| 70 | +) -> Any: |
| 71 | + # Pre-processing |
| 72 | + v = v.strip() if isinstance(v, str) else v |
| 73 | + # Call next validator |
| 74 | + result = handler(v) |
| 75 | + # Post-processing |
| 76 | + return result.upper() |
| 77 | +``` |
| 78 | + |
| 79 | +### `plain` Mode |
| 80 | + |
| 81 | +Plain validators replace Pydantic's validation entirely: |
| 82 | + |
| 83 | +```python |
| 84 | +def plain_validate_name(v: Any) -> str: |
| 85 | + if not isinstance(v, str): |
| 86 | + raise TypeError("Expected string") |
| 87 | + return v |
| 88 | +``` |
| 89 | + |
| 90 | +## Example |
| 91 | + |
| 92 | +### Input Schema |
| 93 | + |
| 94 | +```json |
| 95 | +{ |
| 96 | + "type": "object", |
| 97 | + "title": "User", |
| 98 | + "properties": { |
| 99 | + "name": {"type": "string"}, |
| 100 | + "email": {"type": "string", "format": "email"}, |
| 101 | + "age": {"type": "integer", "minimum": 0} |
| 102 | + }, |
| 103 | + "required": ["name", "email"] |
| 104 | +} |
| 105 | +``` |
| 106 | + |
| 107 | +### Validators File |
| 108 | + |
| 109 | +```json |
| 110 | +{ |
| 111 | + "User": { |
| 112 | + "validators": [ |
| 113 | + { |
| 114 | + "field": "name", |
| 115 | + "function": "myapp.validators.validate_name", |
| 116 | + "mode": "before" |
| 117 | + }, |
| 118 | + { |
| 119 | + "field": "email", |
| 120 | + "function": "myapp.validators.validate_email", |
| 121 | + "mode": "after" |
| 122 | + }, |
| 123 | + { |
| 124 | + "fields": ["name", "email"], |
| 125 | + "function": "myapp.validators.validate_contact_info", |
| 126 | + "mode": "after" |
| 127 | + } |
| 128 | + ] |
| 129 | + } |
| 130 | +} |
| 131 | +``` |
| 132 | + |
| 133 | +### Validator Functions (myapp/validators.py) |
| 134 | + |
| 135 | +```python |
| 136 | +from typing import Any |
| 137 | +from pydantic import ValidationInfo |
| 138 | + |
| 139 | +def validate_name(v: Any, info: ValidationInfo) -> Any: |
| 140 | + if isinstance(v, str): |
| 141 | + return v.strip() |
| 142 | + return v |
| 143 | + |
| 144 | +def validate_email(v: Any, info: ValidationInfo) -> Any: |
| 145 | + if isinstance(v, str) and not v.endswith("@example.com"): |
| 146 | + # Custom email domain validation |
| 147 | + pass |
| 148 | + return v |
| 149 | + |
| 150 | +def validate_contact_info(v: Any, info: ValidationInfo) -> Any: |
| 151 | + # This runs for both name and email fields |
| 152 | + return v |
| 153 | +``` |
| 154 | + |
| 155 | +### Generated Output |
| 156 | + |
| 157 | +```python |
| 158 | +from __future__ import annotations |
| 159 | + |
| 160 | +from typing import Any |
| 161 | + |
| 162 | +from myapp.validators import validate_contact_info, validate_email, validate_name |
| 163 | +from pydantic import BaseModel, EmailStr, ValidationInfo, conint, field_validator |
| 164 | + |
| 165 | + |
| 166 | +class User(BaseModel): |
| 167 | + name: str |
| 168 | + email: EmailStr |
| 169 | + age: conint(ge=0) | None = None |
| 170 | + |
| 171 | + @field_validator('name', mode='before') |
| 172 | + @classmethod |
| 173 | + def validate_name_validator(cls, v: Any, info: ValidationInfo) -> Any: |
| 174 | + return validate_name(v, info) |
| 175 | + |
| 176 | + @field_validator('email', mode='after') |
| 177 | + @classmethod |
| 178 | + def validate_email_validator(cls, v: Any, info: ValidationInfo) -> Any: |
| 179 | + return validate_email(v, info) |
| 180 | + |
| 181 | + @field_validator('name', 'email', mode='after') |
| 182 | + @classmethod |
| 183 | + def validate_contact_info_validator(cls, v: Any, info: ValidationInfo) -> Any: |
| 184 | + return validate_contact_info(v, info) |
| 185 | +``` |
| 186 | + |
| 187 | +## Notes |
| 188 | + |
| 189 | +- This feature only supports Pydantic v2 (`--output-model-type pydantic_v2.BaseModel`) |
| 190 | +- The `ModelName` in the validators file must match the generated Python class name |
| 191 | +- Validator functions are imported automatically based on the `function` path |
| 192 | +- When the same validator function is used multiple times, an incrementing suffix (`_1`, `_2`, etc.) is added to ensure method name uniqueness |
| 193 | + |
| 194 | +--- |
| 195 | + |
| 196 | +## See Also |
| 197 | + |
| 198 | +- [CLI Reference: `--validators`](cli-reference/general-options.md) - CLI option documentation |
| 199 | +- [Pydantic v2 Validators Documentation](https://docs.pydantic.dev/latest/concepts/validators/) - Official Pydantic documentation |
0 commit comments