Custom Regex Errors

class RegexValidator[source]

Bases: object

Base class for creating reusable Pydantic regex validators.

Usage Example

To create a new validator, subclass RegexValidator:

import re

class PasswordValidator(
    RegexValidator,
    pattern=re.compile(r"^(?=.*[A-Z]).{8,}$"),
    error_message="Password must be at least 8 chars with 1 uppercase"
):
    """Validator for user passwords."""
pattern: ClassVar[Pattern[str]]
error_message: ClassVar[str]
classmethod __init_subclass__(pattern: Pattern[str], error_message: str) None[source]

Configure the validator subclass with a specific regex pattern.

Parameters:
  • pattern (Pattern[str]) – The compiled regular expression to validate against.

  • error_message (str) – The custom message returned when validation fails.

classmethod __get_pydantic_core_schema__(source: type[Any], handler: GetCoreSchemaHandler) CoreSchema[source]

Generate the Pydantic Core Schema for the validator.

Integrates the custom regex check into the standard validation chain.