CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-types-jsonschema

Type stubs for jsonschema JSON Schema validation library

Overview
Eval results
Files

format-checker.mddocs/

Format Validation

String format validation system for JSON Schema format keyword validation. This module provides format checkers for common data formats and allows registration of custom format validators.

Capabilities

Format Checker Class

Main class for registering and executing format validation functions.

class FormatChecker:
    """Registry for format validation functions."""
    
    checkers: dict
    
    def __init__(self, formats: Iterable[str] | None = None) -> None:
        """
        Initialize format checker.
        
        Args:
            formats: Specific formats to include (all if None)
        """
    
    def checks(self, format: str, raises: type = FormatError) -> Callable:
        """
        Decorator to register a format checking function.
        
        Args:
            format: Format name to register for
            raises: Exception type to raise on format errors
            
        Returns:
            Decorator function
        """
    
    @classmethod
    def cls_checks(cls, format: str, raises: type = FormatError) -> Callable:
        """
        Class method decorator to register a format checking function.
        
        Args:
            format: Format name to register for
            raises: Exception type to raise on format errors
            
        Returns:
            Decorator function
        """
    
    def check(self, instance: Any, format: str) -> None:
        """
        Check if instance conforms to format.
        
        Args:
            instance: Value to check
            format: Format name to validate against
            
        Raises:
            FormatError: If format validation fails
        """
    
    def conforms(self, instance: Any, format: str) -> bool:
        """
        Check if instance conforms to format without raising.
        
        Args:
            instance: Value to check
            format: Format name to validate against
            
        Returns:
            True if format is valid, False otherwise
        """

Usage example:

from jsonschema import FormatChecker, ValidationError, Draft7Validator

# Create custom format checker
checker = FormatChecker()

@checker.checks('positive-int')
def check_positive_int(instance):
    if not isinstance(instance, int) or instance <= 0:
        raise ValueError("Not a positive integer")
    return True

# Use with validator
schema = {
    "type": "integer",
    "format": "positive-int"
}

validator = Draft7Validator(schema, format_checker=checker)
validator.validate(5)  # Valid
# validator.validate(-1)  # Would raise ValidationError

Pre-configured Format Checkers

Ready-to-use format checkers for different JSON Schema draft versions.

# Draft-specific format checkers with appropriate format support
draft3_format_checker: FormatChecker
draft4_format_checker: FormatChecker  
draft6_format_checker: FormatChecker
draft7_format_checker: FormatChecker

Usage example:

from jsonschema import Draft7Validator, draft7_format_checker

schema = {
    "type": "object",
    "properties": {
        "email": {"type": "string", "format": "email"},
        "website": {"type": "string", "format": "uri"},
        "created": {"type": "string", "format": "date-time"}
    }
}

validator = Draft7Validator(schema, format_checker=draft7_format_checker)

data = {
    "email": "user@example.com",
    "website": "https://example.com",
    "created": "2023-01-01T12:00:00Z"
}

validator.validate(data)  # All formats will be validated

Email Format Validation

Validate email address format.

def is_email(instance: Any) -> bool:
    """
    Check if instance is a valid email address.
    
    Args:
        instance: Value to check
        
    Returns:
        True if valid email format, False otherwise
    """

URI Format Validation

Validate URI and URI reference formats.

def is_uri(instance: Any) -> bool:
    """
    Check if instance is a valid URI.
    
    Args:
        instance: Value to check
        
    Returns:
        True if valid URI format, False otherwise
    """

def is_uri_reference(instance: Any) -> bool:
    """
    Check if instance is a valid URI reference.
    
    Args:
        instance: Value to check
        
    Returns:
        True if valid URI reference format, False otherwise
    """

def is_iri(instance: Any) -> bool:
    """
    Check if instance is a valid IRI (Internationalized Resource Identifier).
    
    Args:
        instance: Value to check
        
    Returns:
        True if valid IRI format, False otherwise
    """

def is_iri_reference(instance: Any) -> bool:
    """
    Check if instance is a valid IRI reference.
    
    Args:
        instance: Value to check
        
    Returns:
        True if valid IRI reference format, False otherwise
    """

IP Address Format Validation

Validate IPv4 and IPv6 address formats.

def is_ipv4(instance: Any) -> bool:
    """
    Check if instance is a valid IPv4 address.
    
    Args:
        instance: Value to check
        
    Returns:
        True if valid IPv4 format, False otherwise
    """

def is_ipv6(instance: Any) -> bool:
    """
    Check if instance is a valid IPv6 address.
    
    Args:
        instance: Value to check
        
    Returns:
        True if valid IPv6 format, False otherwise
    """

Hostname Format Validation

Validate hostname and internationalized domain name formats.

def is_host_name(instance: Any) -> bool:
    """
    Check if instance is a valid hostname.
    
    Args:
        instance: Value to check
        
    Returns:
        True if valid hostname format, False otherwise
    """

def is_idn_host_name(instance: Any) -> bool:
    """
    Check if instance is a valid internationalized domain name.
    
    Args:
        instance: Value to check
        
    Returns:
        True if valid IDN hostname format, False otherwise
    """

Date and Time Format Validation

Validate date, time, and datetime formats according to RFC 3339.

def is_datetime(instance: Any) -> bool:
    """
    Check if instance is a valid RFC 3339 datetime.
    
    Args:
        instance: Value to check
        
    Returns:
        True if valid datetime format, False otherwise
    """

def is_date(instance: Any) -> bool:
    """
    Check if instance is a valid RFC 3339 date.
    
    Args:
        instance: Value to check
        
    Returns:
        True if valid date format, False otherwise
    """

def is_time(instance: Any) -> bool:
    """
    Check if instance is a valid RFC 3339 time.
    
    Args:
        instance: Value to check
        
    Returns:
        True if valid time format, False otherwise
    """

def is_draft3_time(instance: Any) -> bool:
    """
    Check if instance is a valid time according to Draft 3 specification.
    
    Args:
        instance: Value to check
        
    Returns:
        True if valid Draft 3 time format, False otherwise
    """

Regular Expression Format Validation

Validate regular expression format.

def is_regex(instance: Any) -> bool:
    """
    Check if instance is a valid regular expression.
    
    Args:
        instance: Value to check
        
    Returns:
        True if valid regex format, False otherwise
    """

CSS Color Format Validation

Validate CSS color formats.

def is_css_color_code(instance: Any) -> bool:
    """
    Check if instance is a valid CSS color code.
    
    Args:
        instance: Value to check
        
    Returns:
        True if valid CSS color code, False otherwise
    """

def is_css21_color(instance: Any) -> bool:
    """
    Check if instance is a valid CSS 2.1 color.
    
    Args:
        instance: Value to check
        
    Returns:
        True if valid CSS 2.1 color, False otherwise
    """

def is_css3_color(instance: Any) -> bool:
    """
    Check if instance is a valid CSS 3 color.
    
    Args:
        instance: Value to check
        
    Returns:
        True if valid CSS 3 color, False otherwise
    """

JSON Pointer Format Validation

Validate JSON Pointer and relative JSON Pointer formats.

def is_json_pointer(instance: Any) -> bool:
    """
    Check if instance is a valid JSON Pointer (RFC 6901).
    
    Args:
        instance: Value to check
        
    Returns:
        True if valid JSON Pointer format, False otherwise
    """

def is_relative_json_pointer(instance: Any) -> bool:
    """
    Check if instance is a valid relative JSON Pointer.
    
    Args:
        instance: Value to check
        
    Returns:
        True if valid relative JSON Pointer format, False otherwise
    """

URI Template Format Validation

Validate URI template format according to RFC 6570.

def is_uri_template(instance: Any, template_validator: Callable | None = None) -> bool:
    """
    Check if instance is a valid URI template.
    
    Args:
        instance: Value to check
        template_validator: Custom template validator function
        
    Returns:
        True if valid URI template format, False otherwise
    """

Usage Examples

Basic Format Validation

from jsonschema import Draft7Validator, draft7_format_checker

# Email validation
schema = {"type": "string", "format": "email"}
validator = Draft7Validator(schema, format_checker=draft7_format_checker)

validator.validate("user@example.com")  # Valid
# validator.validate("invalid-email")  # ValidationError

# Date validation  
schema = {"type": "string", "format": "date"}
validator = Draft7Validator(schema, format_checker=draft7_format_checker)

validator.validate("2023-12-01")  # Valid
# validator.validate("invalid-date")  # ValidationError

Custom Format Registration

from jsonschema import FormatChecker, Draft7Validator
import re

# Create custom format checker
custom_checker = FormatChecker()

@custom_checker.checks('phone-number')
def check_phone_number(instance):
    pattern = r'^\+?1?-?\.?\s?\(?(\d{3})\)?[\s\-\.]?(\d{3})[\s\-\.]?(\d{4})$'
    if not re.match(pattern, str(instance)):
        raise ValueError("Invalid phone number format")
    return True

# Use with schema
schema = {
    "type": "object", 
    "properties": {
        "phone": {"type": "string", "format": "phone-number"}
    }
}

validator = Draft7Validator(schema, format_checker=custom_checker)
validator.validate({"phone": "+1-555-123-4567"})  # Valid

Combining Format Checkers

from jsonschema import FormatChecker, Draft7Validator, draft7_format_checker

# Extend existing format checker
extended_checker = FormatChecker()

# Add all standard formats
for format_name, format_func in draft7_format_checker.checkers.items():
    extended_checker.checkers[format_name] = format_func

# Add custom format
@extended_checker.checks('custom-id')
def check_custom_id(instance):
    if not isinstance(instance, str) or not instance.startswith('ID-'):
        raise ValueError("Custom ID must start with 'ID-'")
    return True

# Now supports both standard and custom formats
schema = {
    "type": "object",
    "properties": {
        "email": {"type": "string", "format": "email"},
        "id": {"type": "string", "format": "custom-id"}
    }
}

validator = Draft7Validator(schema, format_checker=extended_checker)
validator.validate({"email": "user@example.com", "id": "ID-12345"})

Types

from typing import Any, Callable, Iterable
from jsonschema.exceptions import FormatError

Install with Tessl CLI

npx tessl i tessl/pypi-types-jsonschema

docs

exceptions.md

format-checker.md

index.md

utilities.md

validators.md

tile.json