String validation helps make sure the text data you get is the right size and format. This stops errors and keeps your app safe.
String validation (min, max, regex) in FastAPI
from pydantic import BaseModel, constr class User(BaseModel): name: constr(min_length=3, max_length=20, regex=r'^[a-zA-Z]+$')
constr is used to add string rules like minimum length, maximum length, and regex pattern.
The regex pattern must be a raw string (start with r') to avoid errors.
from pydantic import BaseModel, constr class User(BaseModel): username: constr(min_length=5, max_length=15)
from pydantic import BaseModel, constr class User(BaseModel): code: constr(regex=r'^\d{4}$')
from pydantic import BaseModel, constr class User(BaseModel): password: constr(min_length=8, regex=r'^(?=.*[A-Z])(?=.*\d).+$')
This FastAPI app defines a User model with a username that must be 3-12 characters long and only contain letters, numbers, or underscores. When you send a POST request to /users/ with a valid username, it confirms the username is valid.
from fastapi import FastAPI from pydantic import BaseModel, constr from fastapi.responses import JSONResponse app = FastAPI() class User(BaseModel): username: constr(min_length=3, max_length=12, regex=r'^[a-zA-Z0-9_]+$') @app.post('/users/') async def create_user(user: User): return JSONResponse(content={"message": f"User '{user.username}' is valid!"})
If validation fails, FastAPI automatically returns a clear error message to the client.
Use regex carefully to avoid overly complex patterns that are hard to read.
Always test your validation rules with different inputs to be sure they work as expected.
Use constr from Pydantic to add string validation rules in FastAPI models.
You can set minimum and maximum length and check patterns with regex.
FastAPI handles errors automatically if input does not match the rules.