CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-tortoise-orm

Easy async ORM for Python, built with relations in mind

Overview
Eval results
Files

validators.mddocs/

Validation Framework

Field validation system providing built-in validators for common use cases and base classes for custom validators. Validators ensure data integrity at the application level.

Capabilities

Base Validator

Abstract base class for creating custom validators.

from tortoise.validators import Validator

class Validator(metaclass=abc.ABCMeta):
    """Abstract base class for field validators."""
    
    @abc.abstractmethod
    def __call__(self, value):
        """
        Validate the given value.
        
        Args:
            value: The value to validate
            
        Raises:
            ValidationError: If validation fails
        """

Text Validators

Validators for text and string fields.

from tortoise.validators import RegexValidator, MaxLengthValidator, MinLengthValidator

class RegexValidator(Validator):
    """Validate value matches regular expression pattern."""
    
    def __init__(self, pattern, flags=0):
        """
        Args:
            pattern (str): Regular expression pattern
            flags (int): Regex flags (re.IGNORECASE, etc.)
        """

class MaxLengthValidator(Validator):
    """Validate value length does not exceed maximum."""
    
    def __init__(self, max_length):
        """
        Args:
            max_length (int): Maximum allowed length
        """

class MinLengthValidator(Validator):
    """Validate value length meets minimum requirement."""
    
    def __init__(self, min_length):
        """
        Args:
            min_length (int): Minimum required length
        """

Numeric Validators

Validators for numeric fields.

from tortoise.validators import MinValueValidator, MaxValueValidator

class MinValueValidator(Validator):
    """Validate numeric value meets minimum requirement."""
    
    def __init__(self, min_value):
        """
        Args:
            min_value (int|float|Decimal): Minimum allowed value
        """

class MaxValueValidator(Validator):
    """Validate numeric value does not exceed maximum."""
    
    def __init__(self, max_value):
        """
        Args:
            max_value (int|float|Decimal): Maximum allowed value
        """

Specialized Validators

from tortoise.validators import CommaSeparatedIntegerListValidator

class CommaSeparatedIntegerListValidator(Validator):
    """Validate comma-separated list of integers."""
    
    def __init__(self, sep=","):
        """
        Args:
            sep (str): Separator character (default: comma)
        """

IP Address Validators

Validation functions for IP addresses.

from tortoise.validators import (
    validate_ipv4_address,
    validate_ipv6_address, 
    validate_ipv46_address
)

def validate_ipv4_address(value):
    """
    Validate IPv4 address format.
    
    Args:
        value (str): IP address string
        
    Raises:
        ValidationError: If not valid IPv4 address
    """

def validate_ipv6_address(value):
    """
    Validate IPv6 address format.
    
    Args:
        value (str): IP address string
        
    Raises:
        ValidationError: If not valid IPv6 address
    """

def validate_ipv46_address(value):
    """
    Validate IPv4 or IPv6 address format.
    
    Args:
        value (str): IP address string
        
    Raises:
        ValidationError: If not valid IP address
    """

Usage Examples

Custom Validator

from tortoise.validators import Validator
from tortoise.exceptions import ValidationError
import re

class EmailValidator(Validator):
    """Validate email address format."""
    
    def __init__(self):
        self.pattern = re.compile(r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$')
    
    def __call__(self, value):
        if not self.pattern.match(value):
            raise ValidationError(f"'{value}' is not a valid email address")

# Use in field definition
class User(Model):
    email = CharField(max_length=100, validators=[EmailValidator()])

Built-in Validator Usage

from tortoise.validators import MinLengthValidator, MaxValueValidator
from tortoise.models import Model
from tortoise.fields import CharField, IntField

class User(Model):
    username = CharField(
        max_length=50,
        validators=[MinLengthValidator(3)]
    )
    age = IntField(
        validators=[MaxValueValidator(150)]
    )

Multiple Validators

from tortoise.validators import RegexValidator, MinLengthValidator, MaxLengthValidator

class Product(Model):
    code = CharField(
        max_length=20,
        validators=[
            MinLengthValidator(5),
            MaxLengthValidator(20),
            RegexValidator(r'^[A-Z0-9-]+$', message="Must contain only uppercase letters, numbers, and hyphens")
        ]
    )

IP Address Validation

from tortoise.validators import validate_ipv4_address
from tortoise.fields import CharField

class Server(Model):
    ip_address = CharField(
        max_length=15,
        validators=[validate_ipv4_address]
    )

Validation Process

  1. Field-level validation: Validators run when field values are set
  2. Model validation: All field validators run before saving
  3. Exception handling: ValidationError raised for invalid values
  4. Custom messages: Validators can provide custom error messages

Validators are executed in the order they are defined in the field's validators list.

Install with Tessl CLI

npx tessl i tessl/pypi-tortoise-orm

docs

database.md

exceptions.md

functions.md

index.md

integration.md

models.md

querying.md

signals.md

transactions.md

validators.md

tile.json