0
0
FastAPIframework~5 mins

String validation (min, max, regex) in FastAPI

Choose your learning style9 modes available
Introduction

String validation helps make sure the text data you get is the right size and format. This stops errors and keeps your app safe.

When you want to check a username is not too short or too long.
When you need to make sure a password has certain characters.
When you want to confirm an email address looks correct.
When you want to limit input length to avoid too much data.
When you want to enforce a pattern like phone numbers or codes.
Syntax
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.

Examples
This checks the username is at least 5 and at most 15 characters long.
FastAPI
from pydantic import BaseModel, constr

class User(BaseModel):
    username: constr(min_length=5, max_length=15)
This ensures the code is exactly 4 digits using a regex pattern.
FastAPI
from pydantic import BaseModel, constr

class User(BaseModel):
    code: constr(regex=r'^\d{4}$')
This requires the password to be at least 8 characters, have one uppercase letter and one digit.
FastAPI
from pydantic import BaseModel, constr

class User(BaseModel):
    password: constr(min_length=8, regex=r'^(?=.*[A-Z])(?=.*\d).+$')
Sample Program

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.

FastAPI
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!"})
OutputSuccess
Important Notes

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.

Summary

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.