python
runtime_error
ai_generated
true
PydanticUserError: @field_validator on 'email' requires a classmethod, but the decorator was applied to a regular method. Add @classmethod below @field_validator.
ID: python/pydantic-validator-not-classmethod
80%Fix Rate
90%Confidence
0Evidence
2024-01-22First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 2.x | active | — | — | — |
Root Cause
In Pydantic v2, field_validator must decorate a classmethod; omitting @classmethod causes a PydanticUserError at class definition time.
generic中文
在 Pydantic v2 中,field_validator 必须装饰 classmethod;省略 @classmethod 会在类定义时引发 PydanticUserError。
Workarounds
-
99% success
from pydantic import field_validator class User(BaseModel): email: str @field_validator('email') @classmethod def check_email(cls, v): return v.lower() -
94% success
from typing import Annotated from pydantic import AfterValidator Email = Annotated[str, AfterValidator(lambda v: v.lower())]
Dead Ends
Common approaches that don't work:
-
95% fail
field_validator explicitly checks for classmethod; staticmethod is rejected.
-
90% fail
Validators must be defined inside the model class to be registered.