I am learning FastAPI and SQLmodel on a simple CRUD app. I am trying to validate the "name" field to ensure that it is not empty when a new entry is created in the database.
# Define the SQLModel for the User table
class UserBase(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str = Field(..., min_length=1, nullable=False)
email: str = Field(min_length=1, default=None, unique=True)
password: str = Field(min_length=1)
date_created: datetime = Field(default=datetime.now(), nullable=False)
@validator('name')
def name_must_not_be_empty(cls, v):
if v.strip() == '':
raise ValueError('Name cannot be an empty string')
return v
# Define the schema for a response upon user creation
class CreateUser(BaseModel):
message: str = 'Successfully created user'
id: int
name: str
email: str
# Create a new user
@app.post('/users/', response_model=CreateUser)
def create_user(user: UserBase, session: Session = Depends(get_session)):
session.add(user)
session.commit()
return user
I made the field required and added a validator, yet an empty string can still be passed. What am I missing here?

The solution suggested in the comments; more details available in issue discussion on Github
I will leave an example of the corrected code that performs the required validation.
Models:
Path operation: