Editor

Multiple Field Validation

Advanced · Write the code · from Python Pydantic: Validate Data Like a Pro

From the lesson: Python Pydantic: Validate Data Like a Pro

Every application deals with messy data. User forms with missing fields, API responses with wrong types, config files with invalid values. Data validation is the practice of checking that data matches your expectations before you use it.

Read the lesson

Create a PasswordPolicy dataclass with fields min_length (int), require_uppercase (bool), and require_digits (bool).

Add a method validate_password(self, password: str) -> bool that returns True if the password meets all enabled requirements, False otherwise.

Create a policy with min_length=8, require_uppercase=True, require_digits=True.

Test it with these passwords and print the results:

  • "hello" (should be False)
  • "HelloWorld1" (should be True)
  • "ALLCAPS123" (should be True)
  • from dataclasses import dataclass
    # Create PasswordPolicy dataclass with validate_password method
    # Create policy and test passwords

    More Pydantic exercises

    All Python exercises · 50 practice problems · Advanced Python quiz