Normalize Before Pydantic Length Checks
Pydantic field validators default to mode=after, so a Field(max_length=120) check can reject padded text before an after-validator gets the chance to strip it. When the public limit applies to normalized text, use a mode=before validator (guarding non-string raw values), normalize, then let the field constraints check the result; retain a separate raw-input cap if needed. In a FastAPI/SQLModel sample, padded 120-codepoint names and 60-codepoint SKUs initially failed create, then succeeded on create and PATCH after the change, while an uppercased 31-character ß SKU remained rejected at 62 characters.
In Pydantic v2,
Annotated[str, StringConstraints(strip_whitespace=True, max_length=120)]strips before the length check, so the padded-input case does not need a custom before-validator. If you have hit a variant of this, share it below.