Complete the code to import the validator decorator from pydantic.
from pydantic import BaseModel, [1]
The validator decorator is imported from pydantic to create custom validation methods.
Complete the method decorator to validate the 'name' field.
class User(BaseModel): name: str @[1]('name') def name_must_be_capitalized(cls, v): if not v.istitle(): raise ValueError('Name must be capitalized') return v
The @validator('name') decorator marks the method as a validator for the 'name' field.
Fix the error in the validator method to correctly raise an exception when validation fails.
from pydantic import BaseModel, validator class Product(BaseModel): price: float @validator('price') def price_must_be_positive(cls, v): if v <= 0: raise [1]('Price must be positive') return v
Raising ValueError is the correct way to signal validation errors in Pydantic validators.
Fill both blanks to create a validator that checks the 'email' field is lowercase and contains '@'.
class Contact(BaseModel): email: str @[1]('email') def email_must_be_valid(cls, v): if '@' not in v or v != v.[2](): raise ValueError('Email must be lowercase and contain @') return v
The @validator('email') decorator marks the method for the 'email' field. Using v.lower() checks if the email is lowercase.
Fill all three blanks to create a validator that ensures 'age' is an integer and at least 18.
class Person(BaseModel): age: int @[1]('age') def age_must_be_adult(cls, v): if not isinstance(v, [2]) or v < [3]: raise ValueError('Age must be an integer and at least 18') return v
The @validator('age') decorator marks the method for the 'age' field. isinstance(v, int) checks the type, and 18 is the minimum age.