mirror of
https://github.com/kennethreitz/pydantic.git
synced 2026-06-05 23:00:18 +00:00
Docs: Add validators to dynamic model (#1963)
* Add dynamic validators to doc * Update models_dynamic_validators.py * Update models_dynamic_validators.py * Adding example (success and error) * Update models_dynamic_validators.py
This commit is contained in:
@@ -0,0 +1,26 @@
|
||||
from pydantic import create_model, ValidationError, validator
|
||||
|
||||
|
||||
def username_alphanumeric(cls, v):
|
||||
assert v.isalnum(), 'must be alphanumeric'
|
||||
return v
|
||||
|
||||
|
||||
validators = {
|
||||
'username_validator':
|
||||
validator('username')(username_alphanumeric)
|
||||
}
|
||||
|
||||
UserModel = create_model(
|
||||
'UserModel',
|
||||
username=(str, ...),
|
||||
__validators__=validators
|
||||
)
|
||||
|
||||
user = UserModel(username='scolvin')
|
||||
print(user)
|
||||
|
||||
try:
|
||||
UserModel(username='scolvi%n')
|
||||
except ValidationError as e:
|
||||
print(e)
|
||||
@@ -370,6 +370,12 @@ extending a base model with extra fields.
|
||||
{!.tmp_examples/models_dynamic_inheritance.py!}
|
||||
```
|
||||
|
||||
You can also add validators by passing a dict to the `__validators__` argument.
|
||||
|
||||
```py
|
||||
{!.tmp_examples/models_dynamic_validators.py!}
|
||||
```
|
||||
|
||||
## Custom Root Types
|
||||
|
||||
Pydantic models can be defined with a custom root type by declaring the `__root__` field.
|
||||
|
||||
Reference in New Issue
Block a user