Validators

This module provides comprehensive validation functions for configuration values.

Value validators for configuration.

This module provides validation functions for configuration values: - Numeric validators (port, range, positive, etc.) - String validators (email, URL, IP, domain, etc.) - Collection validators (list length, dict keys, etc.) - File/path validators - Custom validators

For model definition and structure validation, see varlord.model_validation.

exception varlord.validators.ValidationError(key, value, message)[source]

Bases: ValueError

Raised when configuration validation fails.

__init__(key, value, message)[source]

Initialize validation error.

Parameters:
  • key (str) – Configuration key

  • value (Any) – Invalid value

  • message (str) – Error message

varlord.validators.validate_range(value, min=None, max=None)[source]

Validate that a value is within a range.

Parameters:
  • value (Any) – Value to validate

  • min (float | None) – Minimum value (inclusive)

  • max (float | None) – Maximum value (inclusive)

Raises:

ValidationError – If value is out of range

Example

>>> validate_range(50, min=0, max=100)  # OK
>>> validate_range(150, min=0, max=100)  # Raises ValidationError
varlord.validators.validate_regex(value, pattern, flags=0)[source]

Validate that a string matches a regex pattern.

Parameters:
  • value (str) – String to validate

  • pattern (str) – Regex pattern

  • flags (int) – Regex flags

Raises:

ValidationError – If value doesn’t match pattern

Example

>>> validate_regex("abc123", r'^[a-z]+\d+$')  # OK
>>> validate_regex("ABC123", r'^[a-z]+\d+$')  # Raises ValidationError
varlord.validators.validate_choice(value, choices)[source]

Validate that a value is in a list of choices.

Parameters:
  • value (Any) – Value to validate

  • choices (list[Any]) – List of valid choices

Raises:

ValidationError – If value is not in choices

Example

>>> validate_choice("red", ["red", "green", "blue"])  # OK
>>> validate_choice("yellow", ["red", "green", "blue"])  # Raises ValidationError
varlord.validators.validate_not_empty(value)[source]

Validate that a value is not empty.

Parameters:

value (Any) – Value to validate

Raises:

ValidationError – If value is empty

Example

>>> validate_not_empty("hello")  # OK
>>> validate_not_empty(0)  # OK (0 is not considered empty)
>>> validate_not_empty(False)  # OK (False is not considered empty)
>>> validate_not_empty("")  # Raises ValidationError
>>> validate_not_empty([])  # Raises ValidationError
varlord.validators.validate_positive(value)[source]

Validate that a number is positive (> 0).

Parameters:

value (int | float) – Number to validate

Raises:

ValidationError – If value is not positive

Example

>>> validate_positive(10)  # OK
>>> validate_positive(-5)  # Raises ValidationError
varlord.validators.validate_non_negative(value)[source]

Validate that a number is non-negative (>= 0).

Parameters:

value (int | float) – Number to validate

Raises:

ValidationError – If value is negative

Example

>>> validate_non_negative(0)  # OK
>>> validate_non_negative(10)  # OK
>>> validate_non_negative(-5)  # Raises ValidationError
varlord.validators.validate_integer(value)[source]

Validate that a value is an integer.

Parameters:

value (Any) – Value to validate

Raises:

ValidationError – If value is not an integer

Example

>>> validate_integer(42)  # OK
>>> validate_integer(42.5)  # Raises ValidationError
varlord.validators.validate_float(value)[source]

Validate that a value is a float or can be converted to float.

Parameters:

value (Any) – Value to validate

Raises:

ValidationError – If value is not a float

Example

>>> validate_float(3.14)  # OK
>>> validate_float(42)  # OK (int can be float)
>>> validate_float("not a number")  # Raises ValidationError
varlord.validators.validate_percentage(value)[source]

Validate that a number is a valid percentage (0-100).

Parameters:

value (int | float) – Number to validate

Raises:

ValidationError – If value is not in 0-100 range

Example

>>> validate_percentage(50)  # OK
>>> validate_percentage(150)  # Raises ValidationError
varlord.validators.validate_port(value)[source]

Validate that a number is a valid port number (1-65535).

Parameters:

value (int) – Port number to validate

Raises:

ValidationError – If value is not a valid port

Example

>>> validate_port(8080)  # OK
>>> validate_port(70000)  # Raises ValidationError
varlord.validators.validate_greater_than(value, threshold)[source]

Validate that a number is greater than a threshold.

Parameters:
  • value (int | float) – Number to validate

  • threshold (int | float) – Threshold value

Raises:

ValidationError – If value is not greater than threshold

Example

>>> validate_greater_than(10, 5)  # OK
>>> validate_greater_than(3, 5)  # Raises ValidationError
varlord.validators.validate_less_than(value, threshold)[source]

Validate that a number is less than a threshold.

Parameters:
  • value (int | float) – Number to validate

  • threshold (int | float) – Threshold value

Raises:

ValidationError – If value is not less than threshold

Example

>>> validate_less_than(3, 5)  # OK
>>> validate_less_than(10, 5)  # Raises ValidationError
varlord.validators.validate_length(value, min_length=None, max_length=None)[source]

Validate that a string has a length within a range.

Parameters:
  • value (str) – String to validate

  • min_length (int | None) – Minimum length (inclusive)

  • max_length (int | None) – Maximum length (inclusive)

Raises:

ValidationError – If length is out of range

Example

>>> validate_length("hello", min_length=3, max_length=10)  # OK
>>> validate_length("hi", min_length=3)  # Raises ValidationError
varlord.validators.validate_email(value)[source]

Validate that a string is a valid email address.

Parameters:

value (str) – String to validate

Raises:

ValidationError – If value is not a valid email

Example

>>> validate_email("user@example.com")  # OK
>>> validate_email("invalid-email")  # Raises ValidationError
varlord.validators.validate_url(value, require_scheme=True)[source]

Validate that a string is a valid URL.

Parameters:
Raises:

ValidationError – If value is not a valid URL

Example

>>> validate_url("https://example.com")  # OK
>>> validate_url("not-a-url")  # Raises ValidationError
varlord.validators.validate_ipv4(value)[source]

Validate that a string is a valid IPv4 address.

Parameters:

value (str) – String to validate

Raises:

ValidationError – If value is not a valid IPv4 address

Example

>>> validate_ipv4("192.168.1.1")  # OK
>>> validate_ipv4("256.1.1.1")  # Raises ValidationError
varlord.validators.validate_ipv6(value)[source]

Validate that a string is a valid IPv6 address.

Parameters:

value (str) – String to validate

Raises:

ValidationError – If value is not a valid IPv6 address

Example

>>> validate_ipv6("2001:0db8:85a3:0000:0000:8a2e:0370:7334")  # OK
>>> validate_ipv6("192.168.1.1")  # Raises ValidationError
varlord.validators.validate_ip(value)[source]

Validate that a string is a valid IPv4 or IPv6 address.

Parameters:

value (str) – String to validate

Raises:

ValidationError – If value is not a valid IP address

Example

>>> validate_ip("192.168.1.1")  # OK
>>> validate_ip("2001:0db8::1")  # OK
>>> validate_ip("invalid")  # Raises ValidationError
varlord.validators.validate_domain(value)[source]

Validate that a string is a valid domain name.

Parameters:

value (str) – String to validate

Raises:

ValidationError – If value is not a valid domain

Example

>>> validate_domain("example.com")  # OK
>>> validate_domain("sub.example.com")  # OK
>>> validate_domain("invalid..domain")  # Raises ValidationError
varlord.validators.validate_phone(value, country=None)[source]

Validate that a string is a valid phone number.

Parameters:
  • value (str) – String to validate

  • country (str | None) – Country code for validation (e.g., “US”, “CN”). If None, uses generic pattern.

Raises:

ValidationError – If value is not a valid phone number

Example

>>> validate_phone("+1-555-123-4567")  # OK
>>> validate_phone("13800138000")  # OK (Chinese mobile)
>>> validate_phone("invalid")  # Raises ValidationError
varlord.validators.validate_uuid(value, version=None)[source]

Validate that a string is a valid UUID.

Parameters:
  • value (str) – String to validate

  • version (int | None) – UUID version (1-5). If None, accepts any version.

Raises:

ValidationError – If value is not a valid UUID

Example

>>> validate_uuid("550e8400-e29b-41d4-a716-446655440000")  # OK
>>> validate_uuid("invalid-uuid")  # Raises ValidationError
varlord.validators.validate_base64(value)[source]

Validate that a string is valid Base64 encoded data.

Parameters:

value (str) – String to validate

Raises:

ValidationError – If value is not valid Base64

Example

>>> validate_base64("SGVsbG8gV29ybGQ=")  # OK
>>> validate_base64("invalid!")  # Raises ValidationError
varlord.validators.validate_json_string(value)[source]

Validate that a string is valid JSON.

Parameters:

value (str) – String to validate

Raises:

ValidationError – If value is not valid JSON

Example

>>> validate_json_string('{"key": "value"}')  # OK
>>> validate_json_string("invalid json")  # Raises ValidationError
varlord.validators.validate_date_format(value, format='%Y-%m-%d')[source]

Validate that a string matches a date format.

Parameters:
  • value (str) – String to validate

  • format (str) – Date format string (default: “%Y-%m-%d”)

Raises:

ValidationError – If value doesn’t match format

Example

>>> validate_date_format("2024-01-15", "%Y-%m-%d")  # OK
>>> validate_date_format("01/15/2024", "%m/%d/%Y")  # OK
>>> validate_date_format("invalid", "%Y-%m-%d")  # Raises ValidationError
varlord.validators.validate_time_format(value, format='%H:%M:%S')[source]

Validate that a string matches a time format.

Parameters:
  • value (str) – String to validate

  • format (str) – Time format string (default: “%H:%M:%S”)

Raises:

ValidationError – If value doesn’t match format

Example

>>> validate_time_format("14:30:00", "%H:%M:%S")  # OK
>>> validate_time_format("2:30 PM", "%I:%M %p")  # OK
>>> validate_time_format("invalid", "%H:%M:%S")  # Raises ValidationError
varlord.validators.validate_datetime_format(value, format='%Y-%m-%d %H:%M:%S')[source]

Validate that a string matches a datetime format.

Parameters:
  • value (str) – String to validate

  • format (str) – Datetime format string (default: “%Y-%m-%d %H:%M:%S”)

Raises:

ValidationError – If value doesn’t match format

Example

>>> validate_datetime_format("2024-01-15 14:30:00")  # OK
>>> validate_datetime_format("invalid", "%Y-%m-%d %H:%M:%S")  # Raises ValidationError
varlord.validators.validate_list_length(value, min_length=None, max_length=None)[source]

Validate that a list has a length within a range.

Parameters:
  • value (list) – List to validate

  • min_length (int | None) – Minimum length (inclusive)

  • max_length (int | None) – Maximum length (inclusive)

Raises:

ValidationError – If length is out of range

Example

>>> validate_list_length([1, 2, 3], min_length=2, max_length=5)  # OK
>>> validate_list_length([1], min_length=2)  # Raises ValidationError
varlord.validators.validate_dict_keys(value, required_keys=None, allowed_keys=None)[source]

Validate that a dictionary has required keys and/or only allowed keys.

Parameters:
  • value (dict) – Dictionary to validate

  • required_keys (list[str] | None) – List of keys that must be present

  • allowed_keys (list[str] | None) – List of keys that are allowed (if None, all keys allowed)

Raises:

ValidationError – If keys don’t match requirements

Example

>>> validate_dict_keys({"a": 1, "b": 2}, required_keys=["a"])  # OK
>>> validate_dict_keys({"a": 1}, required_keys=["a", "b"])  # Raises ValidationError
>>> validate_dict_keys({"a": 1, "c": 3}, allowed_keys=["a", "b"])  # Raises ValidationError
varlord.validators.validate_file_path(value, must_exist=False)[source]

Validate that a string is a valid file path.

Parameters:
  • value (str) – String to validate

  • must_exist (bool) – Whether the file must exist

Raises:

ValidationError – If value is not a valid file path

Example

>>> validate_file_path("/path/to/file.txt")  # OK
>>> validate_file_path("/nonexistent.txt", must_exist=True)  # Raises ValidationError
varlord.validators.validate_directory_path(value, must_exist=False)[source]

Validate that a string is a valid directory path.

Parameters:
  • value (str) – String to validate

  • must_exist (bool) – Whether the directory must exist

Raises:

ValidationError – If value is not a valid directory path

Example

>>> validate_directory_path("/path/to/dir")  # OK
>>> validate_directory_path("/nonexistent", must_exist=True)  # Raises ValidationError
varlord.validators.validate_custom(value, validator, message='validation failed')[source]

Validate using a custom validator function.

Parameters:
  • value (Any) – Value to validate

  • validator (Callable[[Any], bool]) – Function that returns True if value is valid

  • message (str) – Error message if validation fails

Raises:

ValidationError – If validator returns False

Example

>>> def is_even(n): return n % 2 == 0
>>> validate_custom(4, is_even)  # OK
>>> validate_custom(3, is_even)  # Raises ValidationError
varlord.validators.apply_validators(config, validators)[source]

Apply validators to a configuration object.

Parameters:
  • config (Any) – Configuration object (dataclass instance)

  • validators (dict[str, list[Callable[[Any], None]]]) – Dictionary mapping field names to lists of validator functions

Raises:

ValidationError – If any validation fails

Example

>>> @dataclass
... class Config:
...     port: int = 8000
...     host: str = "localhost"
>>> cfg = Config()
>>> apply_validators(cfg, {
...     "port": [lambda v: validate_port(v)],
...     "host": [lambda v: validate_not_empty(v)]
... })

Validator Categories

The validators are organized into the following categories:

Basic Validators
Numeric Validators
String Validators
Collection Validators
File/Path Validators
Custom Validators