I want to change the validation message from pydantic model class, code for model class is below:
class Input(BaseModel):
ip: IPvAnyAddress
@validator("ip", always=True)
def not_valid_ip(cls, v):
"""To validate ip-address."""
if str(v) == "":
raise ValueError(f'Invalid IP-Address:: {v}')
if not isinstance(v, IPvAnyAddress):
raise ValueError(f'Invalid IP format:: {v}')
return v
currently, it does not update the message written above. I am using fastAPI for API development.
{
"detail": [
{
"loc": [
"body",
"input",
"ip"
],
"msg": "value is not a valid IPv4 or IPv6 address",
"type": "value_error.ipvanyaddress"
}
]
}
That's because the standard validation is failing before your validators is called.
All you need to do is add pre=True to your validator decorator, e.g.
@validator("ip", always=True, pre=True)