pydantic学习与使用-15.校验邮箱格式EmailStr

前言

pydantic 可以使用 EmailStr 校验邮箱格式

环境准备

EmailStr 需按依赖包ImportError: email-validator is not installed, run pip install pydantic[email]

pip install pydantic[email]

校验邮箱格式

from pydantic import BaseModel, EmailStr, validator
from typing import Optional


class User(BaseModel):
    name: str
    age: int
    email: EmailStr
    tel: Optional[str] = None


body = {
    "name": "yoyo",
    "age": 20,
    "email": "aa",
}

a = User(**body)
print(a.dict())

如果邮箱格式不合法,就会报错value is not a valid email address: The email address is not valid

pydantic_core._pydantic_core.ValidationError: 1 validation error for User
email
  value is not a valid email address: The email address is not valid. It must have exactly one @-sign. [type=value_error, input_value='aa', input_type=str]


posted @ 2023-09-07 11:42  上海-悠悠  阅读(635)  评论(0编辑  收藏  举报