CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-validators

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

Overview
Eval results
Files

country-validation.mddocs/

Country and Regional Validation

Validators for country-specific codes, currencies, and regional identifiers. These validators support international standards like ISO 3166 for country codes and ISO 4217 for currency codes.

Capabilities

Country Code Validation

Validates country codes according to ISO 3166 standards in multiple formats.

def country_code(value: str, /, *, iso_format: str = "auto", ignore_case: bool = False) -> Union[Literal[True], ValidationError]:
    """
    Validate ISO 3166 country codes.
    
    Parameters:
    - value: Country code string to validate
    - iso_format: Format to validate ("auto", "alpha2", "alpha3", "numeric")
    - ignore_case: Whether to ignore case sensitivity
    
    Returns:
    True if valid country code, ValidationError otherwise
    
    Supported formats:
    - Alpha-2: 2-letter codes (US, GB, FR)
    - Alpha-3: 3-letter codes (USA, GBR, FRA)  
    - Numeric: 3-digit codes (840, 826, 250)
    - Auto: Automatically detect format based on input
    
    Examples:
    - "US" (Alpha-2), "USA" (Alpha-3), "840" (Numeric) all represent United States
    """

Calling Code Validation

Validates international country calling codes for telephone numbers.

def calling_code(value: str, /) -> Union[Literal[True], ValidationError]:
    """
    Validate country calling codes (phone number prefixes).
    
    Parameters:
    - value: Calling code string to validate (with or without + prefix)
    
    Returns:
    True if valid calling code, ValidationError otherwise
    
    Validates international calling codes:
    - Format: 1-4 digits, optionally prefixed with '+'
    - Examples: +1 (US/Canada), +44 (UK), +33 (France), +86 (China)
    - Supports codes from 1 to 9999
    
    Accepts both "+1" and "1" formats.
    """

Currency Code Validation

Validates currency codes according to ISO 4217 standard.

def currency(value: str, /, *, skip_symbols: bool = True, ignore_case: bool = False) -> Union[Literal[True], ValidationError]:
    """
    Validate ISO 4217 currency codes and symbols.
    
    Parameters:
    - value: Currency code or symbol to validate
    - skip_symbols: Skip validation of currency symbols (default True)
    - ignore_case: Whether to ignore case sensitivity
    
    Returns:
    True if valid currency code/symbol, ValidationError otherwise
    
    Validates:
    - ISO 4217 3-letter currency codes (USD, EUR, GBP, JPY, etc.)
    - Currency symbols when skip_symbols=False ($, €, £, ¥, etc.)
    
    Examples:
    - Currency codes: "USD", "EUR", "GBP", "JPY", "CNY"
    - Currency symbols: "$", "€", "£", "¥", "₹" (when enabled)
    """

Usage Examples

import validators

# Country code validation - Auto detection
validators.country_code('US')        # True (Alpha-2)
validators.country_code('USA')       # True (Alpha-3)
validators.country_code('840')       # True (Numeric)

# Specific format validation
validators.country_code('US', iso_format='alpha2')     # True
validators.country_code('USA', iso_format='alpha3')    # True
validators.country_code('840', iso_format='numeric')   # True

# Case sensitivity
validators.country_code('us')                           # ValidationError (lowercase)
validators.country_code('us', ignore_case=True)        # True

# Invalid country codes
validators.country_code('XX')                           # ValidationError
validators.country_code('INVALID')                      # ValidationError
validators.country_code('999')                          # ValidationError

# Calling code validation
validators.calling_code('+1')       # True (US/Canada)
validators.calling_code('1')        # True (without +)
validators.calling_code('+44')      # True (UK)
validators.calling_code('+33')      # True (France)
validators.calling_code('+86')      # True (China)
validators.calling_code('+91')      # True (India)

# Invalid calling codes
validators.calling_code('0')        # ValidationError
validators.calling_code('+0')       # ValidationError
validators.calling_code('99999')    # ValidationError (too long)

# Currency code validation
validators.currency('USD')          # True
validators.currency('EUR')          # True
validators.currency('GBP')          # True
validators.currency('JPY')          # True
validators.currency('CNY')          # True

# Case sensitivity for currencies
validators.currency('usd')                          # ValidationError (lowercase)
validators.currency('usd', ignore_case=True)       # True

# Currency symbols (when enabled)
validators.currency('$', skip_symbols=False)       # True
validators.currency('€', skip_symbols=False)       # True
validators.currency('£', skip_symbols=False)       # True

# Invalid currencies
validators.currency('XXX')          # ValidationError
validators.currency('INVALID')      # ValidationError

Advanced Usage

Regional Validation Helper

import validators

def validate_regional_data(country: str, phone_code: str, currency_code: str) -> dict:
    """Validate regional data consistency."""
    
    results = {
        'country': bool(validators.country_code(country)),
        'calling_code': bool(validators.calling_code(phone_code)),
        'currency': bool(validators.currency(currency_code))
    }
    
    # Check for common regional consistency
    consistency_checks = {
        ('US', '+1', 'USD'): True,
        ('GB', '+44', 'GBP'): True,
        ('FR', '+33', 'EUR'): True,
        ('DE', '+49', 'EUR'): True,
        ('JP', '+81', 'JPY'): True,
        ('CN', '+86', 'CNY'): True,
    }
    
    results['consistent'] = (country, phone_code, currency_code) in consistency_checks
    results['all_valid'] = all(results[k] for k in ['country', 'calling_code', 'currency'])
    
    return results

# Usage
result = validate_regional_data('US', '+1', 'USD')
print(f"Valid: {result['all_valid']}, Consistent: {result['consistent']}")

Country Code Format Conversion

import validators

# Mapping between country code formats (partial example)
COUNTRY_MAPPINGS = {
    'US': {'alpha3': 'USA', 'numeric': '840', 'name': 'United States'},
    'GB': {'alpha3': 'GBR', 'numeric': '826', 'name': 'United Kingdom'},
    'FR': {'alpha3': 'FRA', 'numeric': '250', 'name': 'France'},
    'DE': {'alpha3': 'DEU', 'numeric': '276', 'name': 'Germany'},
    'JP': {'alpha3': 'JPN', 'numeric': '392', 'name': 'Japan'},
}

def convert_country_code(code: str, target_format: str) -> str:
    """Convert between country code formats."""
    
    # First validate the input code
    if not validators.country_code(code):
        raise ValueError(f"Invalid country code: {code}")
    
    # Determine input format
    if len(code) == 2 and code.isalpha():
        source_format = 'alpha2'
        lookup_key = code.upper()
    elif len(code) == 3 and code.isalpha():
        source_format = 'alpha3'
        # Find alpha2 key by alpha3 value
        lookup_key = None
        for k, v in COUNTRY_MAPPINGS.items():
            if v['alpha3'] == code.upper():
                lookup_key = k
                break
    elif len(code) == 3 and code.isdigit():
        source_format = 'numeric'
        # Find alpha2 key by numeric value
        lookup_key = None
        for k, v in COUNTRY_MAPPINGS.items():
            if v['numeric'] == code:
                lookup_key = k
                break
    else:
        raise ValueError(f"Cannot determine format for: {code}")
    
    if not lookup_key or lookup_key not in COUNTRY_MAPPINGS:
        raise ValueError(f"Country code not found in mapping: {code}")
    
    if target_format == 'alpha2':
        return lookup_key
    elif target_format == 'alpha3':
        return COUNTRY_MAPPINGS[lookup_key]['alpha3']
    elif target_format == 'numeric':
        return COUNTRY_MAPPINGS[lookup_key]['numeric']
    else:
        raise ValueError(f"Invalid target format: {target_format}")

# Usage examples
print(convert_country_code('US', 'alpha3'))    # USA
print(convert_country_code('USA', 'alpha2'))   # US
print(convert_country_code('840', 'alpha2'))   # US

Common Country/Region Combinations

Major Economies

import validators

# Validate major world economies
major_economies = [
    ('US', '+1', 'USD'),     # United States
    ('CN', '+86', 'CNY'),    # China
    ('JP', '+81', 'JPY'),    # Japan
    ('DE', '+49', 'EUR'),    # Germany
    ('GB', '+44', 'GBP'),    # United Kingdom
    ('FR', '+33', 'EUR'),    # France
    ('IN', '+91', 'INR'),    # India
    ('IT', '+39', 'EUR'),    # Italy
    ('BR', '+55', 'BRL'),    # Brazil
    ('CA', '+1', 'CAD'),     # Canada
]

for country, phone, currency in major_economies:
    valid_country = validators.country_code(country)
    valid_phone = validators.calling_code(phone)
    valid_currency = validators.currency(currency)
    
    print(f"{country}: Country={valid_country}, Phone={valid_phone}, Currency={valid_currency}")

European Union Countries

import validators

# EU countries using EUR currency
eu_euro_countries = [
    ('DE', '+49'),  # Germany
    ('FR', '+33'),  # France
    ('IT', '+39'),  # Italy
    ('ES', '+34'),  # Spain
    ('NL', '+31'),  # Netherlands
    ('BE', '+32'),  # Belgium
    ('AT', '+43'),  # Austria
    ('PT', '+351'), # Portugal
    ('IE', '+353'), # Ireland
    ('FI', '+358'), # Finland
]

for country, phone in eu_euro_countries:
    all_valid = (
        validators.country_code(country) and
        validators.calling_code(phone) and
        validators.currency('EUR')
    )
    print(f"{country} + EUR: {all_valid}")

Install with Tessl CLI

npx tessl i tessl/pypi-validators

docs

basic-validation.md

country-validation.md

crypto-validation.md

encoding-validation.md

financial-validation.md

i18n-validation.md

index.md

network-validation.md

system-validation.md

tile.json