Files
pydantic/docs/examples/validators_simple.py
T
Samuel Colvin e7227db41a Insert prints in docs. (#895)
* starting insert prints

* working exec_script

* remove prints, fix exec_examples.py

* more cleanup of examples, better model printing

* upgrade netlify runtime

* extra docs deps

* few more small tweaks
2019-10-14 16:40:25 +01:00

34 lines
944 B
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', username='scolvin', password1='zxcvbn',
password2='zxcvbn'))
try:
UserModel(name='samuel', username='scolvin', password1='zxcvbn',
password2='zxcvbn2')
except ValidationError as e:
print(e)