Created
November 1, 2020 17:32
-
-
Save MartinThoma/1992c38a8262c008da00c01e53c96a34 to your computer and use it in GitHub Desktop.
Example from the docs: https://pydantic-docs.helpmanual.io/usage/validators
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from pydantic import BaseModel, 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.isalnum(), "must be alphanumeric" | |
return v | |
user = UserModel( | |
name="samuel colvin", | |
username="scolvin", | |
password1="zxcvbns", | |
password2="zxcvbn", | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment