or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

basic-validation.mdcountry-validation.mdcrypto-validation.mdencoding-validation.mdfinancial-validation.mdi18n-validation.mdindex.mdnetwork-validation.mdsystem-validation.md
tile.json

tessl/pypi-validators

Python Data Validation for Humans™ - comprehensive validation library for various data types without schema definitions

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/validators@0.35.x

To install, run

npx @tessl/cli install tessl/pypi-validators@0.35.0

index.mddocs/

Validators

Python Data Validation for Humans™ - a comprehensive validation library providing 58+ validation functions for various data types without requiring schema definitions or form definitions. Simply call a function to validate data with immediate True/False results or detailed error information.

Package Information

  • Package Name: validators
  • Language: Python
  • Installation: pip install validators
  • Optional Dependencies: pip install validators[crypto-eth-addresses] for advanced Ethereum validation

Core Imports

Standard import pattern for validators:

import validators

Direct function imports:

from validators import email, url, ipv4, ValidationError

Basic Usage

import validators

# Basic validation - returns True or ValidationError
result = validators.email('user@example.com')
print(result)  # True

# Invalid input returns ValidationError (which evaluates to False)
result = validators.email('invalid-email')
print(bool(result))  # False
print(result)  # ValidationError(func=email, args={'value': 'invalid-email'})

# Force exceptions instead of ValidationError objects  
try:
    validators.url('not-a-url', r_ve=True)  # r_ve = raise ValidationError
except validators.ValidationError as e:
    print(f"Validation failed: {e}")

# Alternative: Set environment variable for global exception mode
import os
os.environ['RAISE_VALIDATION_ERROR'] = 'True'
try:
    validators.email('invalid-email')  # Now raises instead of returning ValidationError
except validators.ValidationError as e:
    print(f"Global exception mode: {e}")

# Multiple validations
data = {
    'email': 'user@example.com',
    'website': 'https://example.com',
    'uuid': '550e8400-e29b-41d4-a716-446655440000'
}

for field, value in data.items():
    if field == 'email' and validators.email(value):
        print(f"✓ Valid {field}")
    elif field == 'website' and validators.url(value):
        print(f"✓ Valid {field}")
    elif field == 'uuid' and validators.uuid(value):
        print(f"✓ Valid {field}")

Architecture

The validators package follows a consistent design pattern:

  • Decorator Pattern: All validators use the @validator decorator that standardizes return behavior
  • ValidationError Class: Unified error handling with function name and argument details
  • Return Convention: Functions return True for valid input or ValidationError for invalid input
  • Boolean Context: ValidationError evaluates to False in boolean contexts
  • Exception Mode: All validators accept an implicit r_ve=True parameter to raise ValidationError exceptions instead of returning them
  • Global Exception Mode: Set RAISE_VALIDATION_ERROR=True environment variable to enable exception raising globally

This architecture enables simple, predictable validation across all data types while providing detailed error information when needed.

Capabilities

Basic Data Validation

Core validators for common data types including ranges, lengths, formats, and identifiers.

def between(value, *, min_val=None, max_val=None): ...
def length(value: str, *, min_val=None, max_val=None): ...  
def uuid(value: Union[str, UUID]): ...
def slug(value: str): ...

Basic Data Validation

Network and Web Validation

Validators for internet-related data including domains, emails, URLs, hostnames, and IP addresses.

def domain(value: str, *, consider_tld=False, rfc_1034=False, rfc_2782=False): ...
def email(value: str, *, ipv6_address=False, ipv4_address=False, simple_host=False, rfc_1034=False, rfc_2782=False): ...
def url(value: str, *, skip_ipv6_addr=False, skip_ipv4_addr=False, may_have_port=True, simple_host=False, strict_query=True, consider_tld=False, private=None, rfc_1034=False, rfc_2782=False): ...
def hostname(value: str, **kwargs): ...
def ipv4(value: str, *, cidr=True, strict=False, private=None, host_bit=True): ...
def ipv6(value: str, *, cidr=True, strict=False, host_bit=True): ...
def mac_address(value: str): ...

Network and Web Validation

Financial Validation

Validators for financial instruments including credit cards, banking codes, and securities identifiers.

def card_number(value: str): ...
def visa(value: str): ...
def mastercard(value: str): ...
def amex(value: str): ...
def unionpay(value: str): ...
def diners(value: str): ...
def jcb(value: str): ...
def discover(value: str): ...
def mir(value: str): ...
def iban(value: str): ...
def cusip(value: str): ...
def isin(value: str): ...
def sedol(value: str): ...

Financial Validation

Encoding and Hash Validation

Validators for various encoding formats and cryptographic hash functions.

def base16(value: str): ...
def base32(value: str): ...
def base58(value: str): ...
def base64(value: str): ...
def md5(value: str): ...
def sha1(value: str): ...
def sha224(value: str): ...
def sha256(value: str): ...
def sha384(value: str): ...
def sha512(value: str): ...

Encoding and Hash Validation

Cryptocurrency Address Validation

Validators for blockchain addresses across major cryptocurrency networks.

def btc_address(value: str): ...
def eth_address(value: str): ...
def bsc_address(value: str): ...
def trx_address(value: str): ...

Cryptocurrency Validation

Country and Regional Validation

Validators for country-specific identifiers, codes, and formats.

def country_code(value: str, *, iso_format="auto", ignore_case=False): ...
def calling_code(value: str): ...
def currency(value: str, *, skip_symbols=True, ignore_case=False): ...

Country and Regional Validation

Internationalization Validation

Validators for country-specific personal and business identifiers.

def es_cif(value: str): ...
def es_nif(value: str): ...
def es_nie(value: str): ...
def es_doi(value: str): ...
def fi_business_id(value: str): ...
def fi_ssn(value: str, *, allow_temporal_ssn=True): ...
def fr_department(value: Union[str, int]): ...
def fr_ssn(value: str): ...
def ind_aadhar(value: str): ...
def ind_pan(value: str): ...
def ru_inn(value: str): ...

Internationalization Validation

System and Time Validation

Validators for system-related formats and time expressions.

def cron(value: str): ...

System Validation

Core Types

class ValidationError(Exception):
    """Exception class for validation failures."""
    
    def __init__(self, function: Callable[..., Any], arg_dict: Dict[str, Any], message: str = ""):
        """Initialize validation failure with function and arguments."""
    
    def __bool__(self) -> bool:
        """Always returns False in boolean context."""
        return False

def validator(func: Callable[..., Any]) -> Callable[..., Union[ValidationError, Literal[True]]]:
    """
    Decorator that makes a function return ValidationError on False, True on success.
    
    The decorated function will:
    - Return Literal[True] for valid inputs
    - Return ValidationError for invalid inputs (evaluates to False in boolean context)
    - Raise ValidationError if r_ve=True parameter is passed or RAISE_VALIDATION_ERROR env var is set
    
    All decorated functions implicitly accept an r_ve parameter:
    - r_ve=True: Raise ValidationError instead of returning it
    - r_ve=False (default): Return ValidationError object
    """