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)
|
||||
Reference in New Issue
Block a user