This is a package that allows to customize pydantic built-in validation error messages
Project description
Pydantic Validation Formatter
Installation
Install package using pip -> pip install pydantic-validation-formatter
Usage
Use @customize_validation_message
decorator on pydantic class to apply message templates on specific validation error message.
from pydantic_validation_formatter import customize_validation_message
from pydantic import BaseModel, Field, ValidationError
@customize_validation_message
class Hero(BaseModel):
id: int = Field(gt=0)
name: str
class Config:
validation_message_template = {
"id": {
"greater_than": "id value should be greater than {gt} but received {input}",
"missing": "id field is required",
},
}
try:
Hero(id=-1, name="hero")
except ValidationError as exc:
print(exc.errors())
This customize the msg
field of validation error as follows -
[
{
'type': 'greater_than',
'loc': ('id',),
'msg': 'id value should be greater than 0 but received -1', # The default generated message will be 'Input should be greater than 0' but it customize the message.
'input': -1,
'ctx': {'gt': 0},
'url': 'https://errors.pydantic.dev/2.6/v/greater_than'
}
]
The validation error message can be templated with following variables
input
- The input value in validation error payloadfield
- The last item inloc
key value from validation error payloaderror_type
- Thetype
key value from validation error payload
If any other keys found in ctx
dict, then you can use those values in templated validation error message.
To provide custom validation templated message, you need to define validation_message_template
attribute in Config
class.
This should be a dict value which contains field name as keys (same as attribute name defined in pydantic class)
and values should be dict of validation error type and customize templated error message mapping.
To know what kind of error type available, follow the official docs -> https://docs.pydantic.dev/latest/errors/validation_errors/
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Hashes for pydantic_validation_formatter-0.1.2.tar.gz
Algorithm | Hash digest | |
---|---|---|
SHA256 | eb458aeb05f328feab7f2bda733db5f9ad165b6285bccf53c806d2d5dc4fc828 |
|
MD5 | 19928b58506911be1e2bc33ed8a6dfe2 |
|
BLAKE2b-256 | f1d5f3d1a438ee9037dfea51fb54f0079427e5f549e56880b41ce861e348e06a |
Hashes for pydantic_validation_formatter-0.1.2-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | ec48d589845fa225fa97e5a84d3082b1f207e67ad2db44fc82a2daee2744f880 |
|
MD5 | 0c2ce497492dfb391d0e4865f88a9a81 |
|
BLAKE2b-256 | f37918b6abd201b360317e03f09e110882973bc69e2fba2af4cfe2ed8c5fd657 |