mirror of
https://github.com/kennethreitz/pydantic.git
synced 2026-06-05 23:00:18 +00:00
f41d5dca3c
* Support assert statements inside validators * Add a validator example that uses assert * Add warning about consequences of using -O optimization flag * Fix a typo * Fix incomplete validator * Extend exception name generation * Improve tests * Clarify pytest behaviour * handle assertion error name, fix build * Address feedback * docs cleanup * Incorporate feedback * fix quotes
42 lines
1.1 KiB
Python
42 lines
1.1 KiB
Python
from pydantic import BaseModel, ValidationError, validator
|
|
|
|
|
|
class UserModel(BaseModel):
|
|
name: str
|
|
username: str
|
|
password1: str
|
|
password2: str
|
|
|
|
@validator('name')
|
|
def name_must_contain_space(cls, v):
|
|
if ' ' not in v:
|
|
raise ValueError('must contain a space')
|
|
return v.title()
|
|
|
|
@validator('password2')
|
|
def passwords_match(cls, v, values, **kwargs):
|
|
if 'password1' in values and v != values['password1']:
|
|
raise ValueError('passwords do not match')
|
|
return v
|
|
|
|
@validator('username')
|
|
def username_alphanumeric(cls, v):
|
|
assert v.isalpha(), 'must be alphanumeric'
|
|
return v
|
|
|
|
|
|
print(UserModel(name='samuel colvin', password1='zxcvbn', password2='zxcvbn'))
|
|
# > UserModel name='Samuel Colvin' password1='zxcvbn' password2='zxcvbn'
|
|
|
|
try:
|
|
UserModel(name='samuel', password1='zxcvbn', password2='zxcvbn2')
|
|
except ValidationError as e:
|
|
print(e)
|
|
"""
|
|
2 validation errors
|
|
name
|
|
must contain a space (type=value_error)
|
|
password2
|
|
passwords do not match (type=value_error)
|
|
"""
|