Skip to content
Sarj Code Standards

prefer-pydantic-field-bounds

Declare simple integer field bounds instead of an after-model validator.

Why

A model-wide validator that only rejects one integer field's literal range hides a field constraint from the schema and adds a separate validation path.

Fix

Consider Field(gt/ge/lt/le) or a constrained Annotated integer. Preserve default validation, validation order, error locations and messages before removing the model validator; this rule offers no automatic rewrite.

Examples

Before — flagged A field range is hidden in a model-wide guard
app/model.py
from pydantic import BaseModel, model_validator
class Count(BaseModel):
value: int
@model_validator(mode="after")
def positive(self):
if self.value < 1:
raise ValueError("must be positive")
return self
After — preferred The field schema declares its range
app/model.py
from pydantic import BaseModel, Field
class Count(BaseModel):
value: int = Field(ge=1)