python data_error ai_generated true

pydantic_core._pydantic_core.ValidationError: 1 validation error for Account username String should have at least 3 characters [type=string_too_short, input_value='ab', input_type=str]

ID: python/pydantic-validation-error-string-too-short

Also available as: JSON · Markdown · 中文
80%Fix Rate
88%Confidence
0Evidence
2024-04-02First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
2.x active — — —

Root Cause

A string field has a min_length constraint and the provided value is shorter than required.

generic

中文

字符串字段设置了 min_length 约束,但提供的值长度不足。

Workarounds

  1. 95% success
    from pydantic import BaseModel, Field
    
    class Account(BaseModel):
        username: str = Field(min_length=3)
    
    # caller side
    try:
        Account(username='ab')
    except ValidationError as e:
        print(e.errors())
  2. 85% success
    username: str = Field(min_length=2)

Dead Ends

Common approaches that don't work:

  1. 75% fail

    Leading/trailing spaces may pass length checks but produce invalid usernames and break downstream uniqueness checks.

  2. 60% fail

    Weakens data integrity; empty or one-character usernames may break UI or DB constraints.