0Pricing
FastAPI Backend Development Bootcamp · درس

التحقق من حقول Pydantic وأدوات التحقق

استكشفوا خيارات التحقق المتقدمة من الحقول وأنشئوا أدوات تحقق مخصّصة لقواعد العمل المعقّدة.

التحقق من حقول Pydantic وأدوات التحقق درس مجاني في FastAPI Backend Development Bootcamp على CoddyKit. هذا هو الدرس 1 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في FastAPI Backend Development Bootcamp، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة FastAPI Backend Development Bootcamp 4 دروس في المجموع.

بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.

Why Validate with Pydantic?

Pydantic automatically validates data types in your models. But sometimes, you need more specific rules, like a minimum length for a username or a positive age.

This is where field validation and custom validators come in! They ensure your data meets all your application's business rules, making your APIs more reliable.

Using Pydantic's `Field` Function

Pydantic's Field function allows you to add extra validation rules and metadata to model fields. It's imported from pydantic. Let's see how to enforce a minimum and maximum length for a string.

from pydantic import BaseModel, Field

class User(BaseModel):
    username: str = Field(min_length=3, max_length=15)
    age: int

# Valid
try:
    user1 = User(username="coddy", age=25)
    print(f"Valid username: {user1.username}")
except Exception as e:
    print(e)

# Invalid username (too short)
try:
    user2 = User(username="c", age=30)
except Exception as e:
    print(f"Error: {e}")

Numeric Field Rules

For numbers, Field offers powerful comparison validators:

  • gt (greater than)
  • lt (less than)
  • ge (greater than or equal to)
  • le (less than or equal to)

Use them to define valid ranges for numeric data, ensuring values are always within expected bounds.

from pydantic import BaseModel, Field

class Product(BaseModel):
    name: str
    price: float = Field(gt=0, le=1000) # Price > 0 and <= 1000
    stock: int = Field(ge=0) # Stock >= 0

# Valid
try:
    product1 = Product(name="Book", price=19.99, stock=100)
    print(f"{product1.name} price: {product1.price}")
except Exception as e:
    print(e)

# Invalid price (negative)
try:
    product2 = Product(name="Pen", price=-5.0, stock=50)
except Exception as e:
    print(f"Error: {e}")

Regex for Field Validation

The pattern argument in Field allows you to validate string fields against a regular expression. This is great for enforcing specific formats, like product codes, serial numbers, or complex identifiers.

from pydantic import BaseModel, Field

class ItemCode(BaseModel):
    # Code must be three uppercase letters, a hyphen, then four digits
    code: str = Field(pattern=r"^[A-Z]{3}-\d{4}$") # e.g., ABC-1234

# Valid
try:
    item1 = ItemCode(code="XYZ-9876")
    print(f"Valid code: {item1.code}")
except Exception as e:
    print(f"Error: {e}")

# Invalid format (lowercase letters)
try:
    item2 = ItemCode(code="abc-1234")
except Exception as e:
    print(f"Error: {e}")

Crafting Custom Validators

While Field covers many common cases, sometimes you need more complex validation logic that involves custom Python code. This is where Pydantic's @validator decorator shines.

You can define a method within your BaseModel and decorate it with @validator('field_name') to apply custom logic to that specific field.

Custom Logic for Fields

Let's create a custom validator to ensure a password field meets specific complexity requirements, like containing at least one digit. The validator function receives the field's value as an argument.

from pydantic import BaseModel, validator
import re

class UserAuth(BaseModel):
    username: str
    password: str

    @validator('password')
    def password_has_digit(cls, v):
        if not re.search(r"\d", v):
            raise ValueError('password must contain at least one digit')
        return v

# Valid
try:
    user1 = UserAuth(username="coder", password="MySecureP@ss1")
    print(f"Password OK for {user1.username}")
except Exception as e:
    print(f"Error: {e}")

# Invalid password (no digits)
try:
    user2 = UserAuth(username="test", password="NoDigitsHere!")
except Exception as e:
    print(f"Error: {e}")

Data Transformation with `pre=True`

Sometimes, you need to transform or clean incoming data before Pydantic's standard type validation or other validators run. For this, use @validator('field_name', pre=True).

A common use case is stripping whitespace or converting case before validating the content, ensuring consistency.

from pydantic import BaseModel, validator

class SearchQuery(BaseModel):
    query: str

    @validator('query', pre=True)
    def strip_whitespace(cls, v):
        if isinstance(v, str):
            return v.strip()
        return v # Pydantic will handle type validation later

# Input with leading/trailing spaces
query1 = SearchQuery(query="   python tutorial   ")
print(f"Cleaned query: '{query1.query}'")

# Input without spaces
query2 = SearchQuery(query="fastapi")
print(f"Cleaned query: '{query2.query}'")

Stacking Field Validators

You can apply multiple @validator decorators to a single field. They will execute in the order they are defined. This allows you to chain validation logic, making your models robust.

For list fields, use each_item=True to apply the validator to every element in the list.

from pydantic import BaseModel, validator

class TagList(BaseModel):
    tags: list[str]

    @validator('tags', each_item=True)
    def tag_must_be_lowercase(cls, v):
        if v != v.lower():
            raise ValueError('tag must be lowercase')
        return v

    @validator('tags', each_item=True)
    def tag_min_length(cls, v):
        if len(v) < 2:
            raise ValueError('tag must be at least 2 chars')
        return v

# Valid
try:
    tags1 = TagList(tags=["python", "fastapi"])
    print(f"Tags OK: {tags1.tags}")
except Exception as e:
    print(f"Error: {e}")

# Invalid (uppercase and too short)
try:
    tags2 = TagList(tags=["PY", "a"])
except Exception as e:
    print(f"Error: {e}")

Cross-Field Validation with Root Validators

Sometimes, the validity of one field depends on the value of another field (or multiple others). This is called cross-field validation. Pydantic's @root_validator allows you to validate the entire model's data dictionary at once.

It's useful for scenarios like ensuring a start_date is before an end_date, or that password and confirm_password match.

Root Validator in Action

The @root_validator receives the entire model's data as a dictionary. You can use pre=True or pre=False (default) to run before or after field-specific validation. Post-validation (default) is usually preferred for cross-field checks.

from pydantic import BaseModel, root_validator, ValidationError

class Registration(BaseModel):
    email: str
    password: str
    password_confirm: str

    @root_validator()
    def passwords_match(cls, values):
        pw1, pw2 = values.get('password'), values.get('password_confirm')
        if pw1 is not None and pw2 is not None and pw1 != pw2:
            raise ValueError('passwords do not match')
        return values

# Valid
try:
    reg1 = Registration(email="a@b.com", password="P@ssword1", password_confirm="P@ssword1")
    print("Registration valid!")
except ValidationError as e:
    print(f"Error: {e}")

# Invalid (passwords don't match)
try:
    reg2 = Registration(email="x@y.com", password="P@ssword1", password_confirm="P@ssword2")
except ValidationError as e:
    print(f"Error: {e}")

Validation Checkpoint

Consider the following Pydantic model for a user profile:

from pydantic import BaseModel, Field, validator
import re

class UserProfile(BaseModel):
    username: str = Field(min_length=5, max_length=20)
    email: str
    age: int = Field(gt=18)
    bio: str = ""

    @validator('email')
    def validate_email_format(cls, v):
        if not re.match(r"[^@]+@[^@]+\.[^@]+", v):
            raise ValueError('Invalid email format')
        return v

Which of the following JSON inputs would be valid for UserProfile?

Recap: Mastering Validation

You've learned how to make your data models truly robust!

  • Field: For built-in rules like min/max length, numeric ranges, and regex patterns.
  • @validator: To implement custom logic for individual fields, with pre=True for early transformation.
  • @root_validator: For complex cross-field validation that depends on multiple fields.

These tools empower you to define precise rules, ensuring data integrity in your FastAPI applications. Keep practicing to build even more reliable APIs!

الأسئلة الشائعة

هل درس «التحقق من حقول Pydantic وأدوات التحقق» مجاني؟

نعم — نص درس «التحقق من حقول Pydantic وأدوات التحقق» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة FastAPI Backend Development Bootcamp، انتقل إلى CoddyKit PRO. تتضمن دورة FastAPI Backend Development Bootcamp 4 دروس في المجموع.

ماذا ستتعلم في «التحقق من حقول Pydantic وأدوات التحقق»؟

استكشفوا خيارات التحقق المتقدمة من الحقول وأنشئوا أدوات تحقق مخصّصة لقواعد العمل المعقّدة. تتمرن على FastAPI Backend Development Bootcamp مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.

هل أحتاج إلى خبرة سابقة لأبدأ FastAPI Backend Development Bootcamp؟

لا تُشترط خبرة سابقة. FastAPI Backend Development Bootcamp على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 1 من أصل 4.

كم من الوقت يستغرق درس «التحقق من حقول Pydantic وأدوات التحقق»؟

معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.

هل يمكنني كتابة وتشغيل أكواد في درس FastAPI Backend Development Bootcamp هذا؟

نعم. كل درس في FastAPI Backend Development Bootcamp يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.

جميع الدروس في هذه الدورة

  1. التحقق من حقول Pydantic وأدوات التحقق
  2. أنواع البيانات المخصّصة والإعدادات
  3. النماذج المتداخلة والبنى التكرارية
  4. التسلسل باستخدام model_dump والأسماء المستعارة
← العودة إلى FastAPI Backend Development Bootcamp