A schema and validator for YAML with comprehensive data type validation and constraint support.
Comprehensive set of validators for all common data types with constraint support for building robust validation schemas. Yamale provides validators for primitive types, collections, patterns, and specialized formats.
All validators inherit from the base Validator class and support common parameters.
class Validator:
"""
Base class for all validators.
"""
def __init__(self, *args, **kwargs):
"""
Initialize validator with arguments and constraints.
Common Parameters:
- required (bool): Whether field is required (default: True)
- none (bool): Whether None values are allowed for optional fields (default: True)
Attributes:
- args: Positional arguments passed to validator
- kwargs: Keyword arguments passed to validator
- is_required: Whether field is required
- constraints: List of constraint classes for this validator
- value_type: Expected value type for this validator
"""
def validate(self, value):
"""
Validate a value against this validator.
Parameters:
- value: Value to validate
Returns:
list: List of error messages (empty if valid)
"""
def is_valid(self, value):
"""
Check if value is valid (returns boolean).
Parameters:
- value: Value to validate
Returns:
bool: True if valid, False otherwise
"""
def fail(self, value):
"""
Generate error message for invalid value.
Parameters:
- value: The invalid value
Returns:
str: Error message
"""
def get_name(self):
"""
Get display name for this validator.
Returns:
str: Validator name for error messages
"""
@property
def tag(self):
"""Validator tag used in schema syntax."""
@property
def is_optional(self):
"""Whether this validator allows optional fields."""
@property
def can_be_none(self):
"""Whether None values are accepted for optional fields."""
# Common constraint attributes
constraints: list # List of constraint classes
value_type: type # Expected Python type
args: tuple # Validator arguments
kwargs: dict # Validator keyword arguments
is_required: bool # Whether field is requiredValidates string values with extensive constraint options for length, content, and pattern matching.
class String(Validator):
"""
String validator with comprehensive constraint support.
Schema syntax: str(min=int, max=int, equals=str, starts_with=str, ends_with=str, matches=regex, exclude=str, ignore_case=bool, multiline=bool, dotall=bool)
"""Constraint parameters:
min: Minimum string lengthmax: Maximum string lengthequals: Exact string match (case-sensitive by default)starts_with: String must start with specified valueends_with: String must end with specified valuematches: Regular expression pattern matchingexclude: Reject strings containing any character from excluded setignore_case: Case-insensitive matching for equals/starts_with/ends_with/matchesmultiline: Enable multiline regex mode (only with matches)dotall: Enable dotall regex mode (only with matches)Schema examples:
# Basic string validation
name: str()
# Length constraints
username: str(min=3, max=20)
# Content validation
status: str(equals="active")
filename: str(ends_with=".yaml")
url: str(starts_with="https://")
# Pattern validation
email: str(matches="^[^@]+@[^@]+\.[^@]+$")
clean_input: str(exclude="<>\"'")
# Case-insensitive matching
status: str(equals="Active", ignore_case=True)Validators for integer and floating-point numbers with range constraints.
class Integer(Validator):
"""
Integer validator with range constraints.
Schema syntax: int(min=int, max=int)
"""
class Number(Validator):
"""
Number validator for integers and floats with range constraints.
Schema syntax: num(min=float, max=float)
"""Schema examples:
# Basic numeric validation
age: int()
score: num()
# Range constraints
port: int(min=1, max=65535)
percentage: num(min=0.0, max=100.0)
temperature: num(min=-273.15) # Absolute zero minimumSimple validators for boolean and null values.
class Boolean(Validator):
"""
Boolean validator.
Schema syntax: bool()
"""
class Null(Validator):
"""
Null/None validator.
Schema syntax: null()
"""Schema examples:
# Boolean validation
enabled: bool()
debug_mode: bool()
# Null validation
optional_field: null()Validators for lists and maps with content and size constraints.
class List(Validator):
"""
List validator with element type and size constraints.
Schema syntax: list([validators], min=int, max=int)
"""
class Map(Validator):
"""
Map/dictionary validator with key/value type and size constraints.
Schema syntax: map([value_validators], key=key_validator, min=int, max=int)
"""Schema examples:
# Basic collections
tags: list()
metadata: map()
# Typed collections
scores: list(int())
user_data: map(str()) # Values must be strings
# Size constraints
required_items: list(str(), min=1, max=5)
small_config: map(any(), max=10)
# Key type validation
numeric_lookup: map(str(), key=int()) # Integer keys, string values
# Complex nested validation
users: list(include('user'))
permissions: map(list(str()), key=str()) # String keys, list of strings valuesValidators for enumerated values and union types.
class Enum(Validator):
"""
Enum validator for fixed set of allowed values.
Schema syntax: enum(value1, value2, ...)
"""
class Any(Validator):
"""
Any validator - accepts one of several validator types.
Schema syntax: any([validators])
"""
class Subset(Validator):
"""
Subset validator - accepts one or more of several validator types as a list.
Schema syntax: subset([validators], allow_empty=bool)
"""Schema examples:
# Enumerated values
status: enum('draft', 'published', 'archived')
priority: enum(1, 2, 3, 'high', 'medium', 'low')
# Union types
id: any(int(), str()) # Either integer or string
config_value: any(str(), num(), bool())
# Subset validation (automatically validates as list)
permissions: subset(str()) # List of strings
mixed_data: subset(int(), str(), bool()) # List containing any combination
# Allow empty subsets
optional_tags: subset(str(), allow_empty=True)Advanced pattern matching with regular expressions.
class Regex(Validator):
"""
Regular expression validator with multiple pattern support.
Schema syntax: regex(pattern1, pattern2, ..., name=str, ignore_case=bool, multiline=bool, dotall=bool)
"""Schema examples:
# Basic pattern matching
ssn: regex('^\\d{3}-\\d{2}-\\d{4}$')
# Multiple acceptable patterns
phone: regex('^\\d{10}$', '^\\d{3}-\\d{3}-\\d{4}$', '^\\(\\d{3}\\)\\s\\d{3}-\\d{4}$')
# Named patterns for better error messages
user_id: regex('^[a-zA-Z0-9_]+$', name='alphanumeric identifier')
# Case-insensitive matching
code: regex('^[A-Z]{2,4}$', ignore_case=True)
# Multiline patterns
text_block: regex('.*^Summary:', multiline=True, dotall=True)Validators for date and timestamp formats with range constraints.
class Day(Validator):
"""
Date validator for YYYY-MM-DD format.
Schema syntax: day(min=date_str, max=date_str)
"""
class Timestamp(Validator):
"""
Timestamp validator for YYYY-MM-DD HH:MM:SS format.
Schema syntax: timestamp(min=timestamp_str, max=timestamp_str)
"""Schema examples:
# Date validation
birth_date: day()
start_date: day(min='2020-01-01')
end_date: day(max='2030-12-31')
project_date: day(min='2023-01-01', max='2023-12-31')
# Timestamp validation
created_at: timestamp()
login_time: timestamp(min='2023-01-01 00:00:00')
scheduled_time: timestamp(min='2023-06-01 09:00:00', max='2023-06-01 17:00:00')Specialized validators for network addresses and version strings.
class Ip(Validator):
"""
IP address validator for IPv4 and IPv6.
Schema syntax: ip(version=int)
"""
class Mac(Validator):
"""
MAC address validator.
Schema syntax: mac()
"""
class SemVer(Validator):
"""
Semantic versioning validator.
Schema syntax: semver()
"""Schema examples:
# Network addresses
server_ip: ip()
ipv4_only: ip(version=4)
ipv6_only: ip(version=6)
device_mac: mac()
# Version strings
package_version: semver() # e.g., "1.2.3", "2.0.0-alpha.1"Validator for referencing defined schema includes.
class Include(Validator):
"""
Include validator for referencing schema includes.
Schema syntax: include('include_name', strict=bool)
"""Schema examples:
# Basic include usage
user: include('person')
admin: include('person')
# Include with strict mode control
flexible_user: include('person', strict=False) # Allow extra fields
strict_config: include('settings') # Default strict mode
---
# Include definitions
person:
name: str()
age: int(min=0)
settings:
debug: bool()
timeout: int()Yamale supports creating custom validators by extending the base Validator class.
class CustomValidator(Validator):
"""
Base class for creating custom validators.
"""
tag = "custom_name" # Schema syntax identifier
def _is_valid(self, value):
"""
Implement validation logic.
Parameters:
- value: Value to validate
Returns:
bool: True if valid, False otherwise
"""Example custom validator:
import yamale
from yamale.validators import Validator, DefaultValidators
class EmailValidator(Validator):
tag = 'email'
def _is_valid(self, value):
if not isinstance(value, str):
return False
return '@' in value and '.' in value and len(value) > 5
# Register custom validator
custom_validators = DefaultValidators.copy()
custom_validators['email'] = EmailValidator
# Use in schema
schema = yamale.make_schema(
content="contact: email()",
validators=custom_validators
)DefaultValidators = {
# Access dictionary mapping validator tags to classes
'str': String,
'int': Integer,
'num': Number,
'bool': Boolean,
'null': Null,
'list': List,
'map': Map,
'enum': Enum,
'any': Any,
'subset': Subset,
'include': Include,
'regex': Regex,
'day': Day,
'timestamp': Timestamp,
'ip': Ip,
'mac': Mac,
'semver': SemVer,
# Also accessible by class name: 'String': String, etc.
}This dictionary is used by default when creating schemas and can be extended with custom validators.
Install with Tessl CLI
npx tessl i tessl/pypi-yamale