mirror of
https://github.com/kennethreitz/pydantic.git
synced 2026-06-05 23:00:18 +00:00
1d0d98ba19
* root validators and rename __obj__ -> __root__ * implement root validation * tweak Validator * dataclass and generic tests, docs * repeat and signature checks * fix inheritance * tweaks tests and var names * improvements to 'from_orm' to work better with root validators (#822) * improvements to 'from_orm' to work better with root validators * cython compatibility and tweaks * tweak config order * added test for derived classes using custom getter_dict config (#833) * added test for derived classes using custom getter_dict config * fix linting * fix formatting * cleanup
42 lines
1.2 KiB
Python
42 lines
1.2 KiB
Python
from pydantic import BaseModel, ValidationError, root_validator
|
|
|
|
class UserModel(BaseModel):
|
|
username: str
|
|
password1: str
|
|
password2: str
|
|
|
|
@root_validator(pre=True)
|
|
def check_card_number_omitted(cls, values):
|
|
assert 'card_number' not in values, 'card_number should not be included'
|
|
return values
|
|
|
|
@root_validator
|
|
def check_passwords_match(cls, values):
|
|
pw1, pw2 = values.get('password1'), values.get('password2')
|
|
if pw1 is not None and pw2 is not None and pw1 != pw2:
|
|
raise ValueError('passwords do not match')
|
|
return values
|
|
|
|
print(UserModel(username='scolvin', password1='zxcvbn', password2='zxcvbn'))
|
|
#> UserModel username='scolvin' password1='zxcvbn' password2='zxcvbn'
|
|
|
|
try:
|
|
UserModel(username='scolvin', password1='zxcvbn', password2='zxcvbn2')
|
|
except ValidationError as e:
|
|
print(e)
|
|
"""
|
|
1 validation error for UserModel
|
|
__root__
|
|
passwords do not match (type=value_error)
|
|
"""
|
|
|
|
try:
|
|
UserModel(username='scolvin', password1='zxcvbn', password2='zxcvbn', card_number='1234')
|
|
except ValidationError as e:
|
|
print(e)
|
|
"""
|
|
1 validation error for UserModel
|
|
__root__
|
|
card_number should not be included (type=assertion_error)
|
|
"""
|