mirror of
https://github.com/kennethreitz/pydantic.git
synced 2026-06-05 23:00:18 +00:00
e00dba322b
* 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
27 lines
487 B
Python
27 lines
487 B
Python
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)
|