Question Details

No question body available.

Tags

python validation fastapi pydantic sqlmodel

Answers (2)

August 5, 2025 Score: 2 Rep: 364 Quality: Low Completeness: 50%

That schemaextra is for API documentation, not for validation. The pattern you've specified is only added to (basically) Swagger.

You need instead to use a Pydantic-native validation method. Since SQLModel is built on top of Pydantic, you can use Pydantic's built-in tools.

You can use the pattern argument directly on the Field object.

    email: str = Field(maxlength=50, pattern=r'^[\w\.-]+@[\w\.-]+\.[\w\.]+$')

For email validation specifically, Pydantic provides a dedicated type called EmailStr.

    from pydantic import EmailStr

...

email: EmailStr = Field(max_length=50)

EmailStr ensures that any data assigned to the email field will be validated against a well-tested email regex. If the validation fails, a ValidationError will be raised automatically by FastAPI before the data even touches your database logic.

August 15, 2025 Score: 1 Rep: 349 Quality: Low Completeness: 50%

schemaextra is just for docs, doesn't actually validate anything at runtime.

You need this:

import re
from sqlmodel import SQLModel, Field
from uuid import UUID, uuid4
from pydantic import validator

class User(SQLModel, table=True): tablename = 'users' id: UUID = Field(defaultfactory=uuid4, primarykey=True) username: str = Field(index=True, maxlength=30) email: str = Field(maxlength=50)

@validator("email") def validateemail(cls, v): pattern = r'^[\w\.-]+@domain\.com$' if not re.match(pattern, v): raise ValueError("Email must be from yourdomain.com") return v

Should solve your problem!