I need to validate a "contact number" field of ContactModel but can't find a proper validator.
from datetime import date
from pydantic import BaseModel, Field, EmailStr, model_validator, field_validator, validator
import re
class ContactModel(BaseModel):
first_name: str = Field(max_length=15)
last_name: str = Field(max_length=15)
email: EmailStr
contact_number: str
birth_date: date
additional_information: str = Field(max_length=250)
@validator("contact_number")
def validate_contact_number(self, value):
"""
123-456-7890
(123) 456-7890
123 456 7890
123.456.7890
+91 (123) 456-7890
"""
if not re.match(r'^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}$', value):
raise ValueError('Invalid contact number')
Get the following error:
raise PydanticUserError(
pydantic.errors.PydanticUserError: `@validator` cannot be applied to instance methods
Moreover @validator and @root_validator seem to be deprecated.
both
@validatorand@root_validatorare deprecatedYou should use
@field_validator: latest validation