前言
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.model_dump())
如果邮箱格式不合法,就会报错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]
标签:15,valid,EmailStr,address,邮箱,email,pydantic
From: https://www.cnblogs.com/yoyoketang/p/17684432.html