Skip to content

Validation

Framework for validating string values

Failure class

Information about a validation failure.

description class-attribute instance-attribute

description: str | None = None

An optional override for describing this failure. Takes precedence over any messages set in the Validator.

validator instance-attribute

validator: Validator

The Validator which produced the failure.

value class-attribute instance-attribute

value: str | None = None

The value which resulted in validation failing.

Function class

def __init__(self, function, failure_description=None):

Bases: Validator

A flexible validator which allows you to provide custom validation logic.

function instance-attribute

function = function

Function which takes the value to validate and returns True if valid, and False otherwise.

ReturnedFalse class

Bases: Failure

Indicates validation failed because the supplied function returned False.

describe_failure method

def describe_failure(self, failure):

Describes why the validator failed.

Parameters
Name Type Description Default
failure Failure

Information about why the validation failed.

required
Returns
Type Description
str | None

A string description of the failure.

validate method

def validate(self, value):

Validate that the supplied function returns True.

Parameters
Name Type Description Default
value str

The value to pass into the supplied function.

required
Returns
Type Description
ValidationResult

A ValidationResult indicating success if the function returned True, and failure if the function return False.

Integer class

Bases: Number

Validator which ensures the value is an integer which falls within a range.

NotAnInteger class

Bases: Failure

Indicates a failure due to the value not being a valid integer.

describe_failure method

def describe_failure(self, failure):

Describes why the validator failed.

Parameters
Name Type Description Default
failure Failure

Information about why the validation failed.

required
Returns
Type Description
str | None

A string description of the failure.

validate method

def validate(self, value):

Ensure that value is an integer, optionally within a range.

Parameters
Name Type Description Default
value str

The value to validate.

required
Returns
Type Description
ValidationResult

The result of the validation.

Length class

def __init__(
    self,
    minimum=None,
    maximum=None,
    failure_description=None,
):

Bases: Validator

Validate that a string is within a range (inclusive).

maximum instance-attribute

maximum = maximum

The inclusive maximum length of the value, or None if unbounded.

minimum instance-attribute

minimum = minimum

The inclusive minimum length of the value, or None if unbounded.

Incorrect class

Bases: Failure

Indicates a failure due to the length of the value being outside the range.

describe_failure method

def describe_failure(self, failure):

Describes why the validator failed.

Parameters
Name Type Description Default
failure Failure

Information about why the validation failed.

required
Returns
Type Description
str | None

A string description of the failure.

validate method

def validate(self, value):

Ensure that value falls within the maximum and minimum length constraints.

Parameters
Name Type Description Default
value str

The value to validate.

required
Returns
Type Description
ValidationResult

The result of the validation.

Number class

def __init__(
    self,
    minimum=None,
    maximum=None,
    failure_description=None,
):

Bases: Validator

Validator that ensures the value is a number, with an optional range check.

maximum instance-attribute

maximum = maximum

The maximum value of the number, inclusive. If None, the maximum is unbounded.

minimum instance-attribute

minimum = minimum

The minimum value of the number, inclusive. If None, the minimum is unbounded.

NotANumber class

Bases: Failure

Indicates a failure due to the value not being a valid number (decimal/integer, inc. scientific notation)

NotInRange class

Bases: Failure

Indicates a failure due to the number not being within the range [minimum, maximum].

describe_failure method

def describe_failure(self, failure):

Describes why the validator failed.

Parameters
Name Type Description Default
failure Failure

Information about why the validation failed.

required
Returns
Type Description
str | None

A string description of the failure.

validate method

def validate(self, value):

Ensure that value is a valid number, optionally within a range.

Parameters
Name Type Description Default
value str

The value to validate.

required
Returns
Type Description
ValidationResult

The result of the validation.

Regex class

def __init__(self, regex, flags=0, failure_description=None):

Bases: Validator

A validator that checks the value matches a regex (via re.fullmatch).

flags instance-attribute

flags = flags

The flags to pass to re.fullmatch.

regex instance-attribute

regex = regex

The regex which we'll validate is matched by the value.

NoResults class

Bases: Failure

Indicates validation failed because the regex could not be found within the value string.

describe_failure method

def describe_failure(self, failure):

Describes why the validator failed.

Parameters
Name Type Description Default
failure Failure

Information about why the validation failed.

required
Returns
Type Description
str | None

A string description of the failure.

validate method

def validate(self, value):

Ensure that the value matches the regex.

Parameters
Name Type Description Default
value str

The value that should match the regex.

required
Returns
Type Description
ValidationResult

The result of the validation.

URL class

Bases: Validator

Validator that checks if a URL is valid (ensuring a scheme is present).

InvalidURL class

Bases: Failure

Indicates that the URL is not valid.

describe_failure method

def describe_failure(self, failure):

Describes why the validator failed.

Parameters
Name Type Description Default
failure Failure

Information about why the validation failed.

required
Returns
Type Description
str | None

A string description of the failure.

validate method

def validate(self, value):

Validates that value is a valid URL (contains a scheme).

Parameters
Name Type Description Default
value str

The value to validate.

required
Returns
Type Description
ValidationResult

The result of the validation.

ValidationResult class

The result of calling a Validator.validate method.

failure_descriptions property

failure_descriptions: list[str]

Utility for extracting failure descriptions as strings.

Useful if you don't care about the additional metadata included in the Failure objects.

Returns
Type Description
list[str]

A list of the string descriptions explaining the failing validations.

failures class-attribute instance-attribute

failures: Sequence[Failure] = field(default_factory=list)

A list of reasons why the value was invalid. Empty if valid=True

is_valid property

is_valid: bool

True if the validation was successful.

failure staticmethod

def failure(failures):

Construct a failure ValidationResult.

Parameters
Name Type Description Default
failures Sequence[Failure]

The failures.

required
Returns
Type Description
ValidationResult

A failure ValidationResult.

merge staticmethod

def merge(results):

Merge multiple ValidationResult objects into one.

Parameters
Name Type Description Default
results Sequence['ValidationResult']

List of ValidationResult objects to merge.

required
Returns
Type Description
'ValidationResult'

Merged ValidationResult object.

success staticmethod

def success():

Construct a successful ValidationResult.

Returns
Type Description
ValidationResult

A successful ValidationResult.

Validator class

def __init__(self, failure_description=None):

Bases: ABC

Base class for the validation of string values.

Commonly used in conjunction with the Input widget, which accepts a list of validators via its constructor. This validation framework can also be used to validate any 'stringly-typed' values (for example raw command line input from sys.args).

To implement your own Validator, subclass this class.

Example
class Palindrome(Validator):
    def validate(self, value: str) -> ValidationResult:
        def is_palindrome(value: str) -> bool:
            return value == value[::-1]
        return self.success() if is_palindrome(value) else self.failure("Not palindrome!")

failure_description instance-attribute

failure_description = failure_description

A description of why the validation failed.

The description (intended to be user-facing) to attached to the Failure if the validation fails. This failure description is ultimately accessible at the time of validation failure via the Input.Changed or Input.Submitted event, and you can access it on your message handler (a method called, for example, on_input_changed or a method decorated with @on(Input.Changed).

describe_failure method

def describe_failure(self, failure):

Return a string description of the Failure.

Used to provide a more fine-grained description of the failure. A Validator could fail for multiple reasons, so this method could be used to provide a different reason for different types of failure.

Warning

This method is only called if no other description has been supplied. If you supply a description inside a call to self.failure(description="..."), or pass a description into the constructor of the validator, those will take priority, and this method won't be called.

Parameters
Name Type Description Default
failure Failure

Information about why the validation failed.

required
Returns
Type Description
str | None

A string description of the failure.

failure method

def failure(self, description=None, value=None, failures=None):

Shorthand for signaling validation failure.

You can return failure(...) from a Validator.validate implementation to signal validation succeeded.

Parameters
Name Type Description Default
description str | None

The failure description that will be used. When used in conjunction with the Input widget, this is the description that will ultimately be available inside the handler for Input.Changed. If not supplied, the failure_description from the Validator will be used. If that is not supplied either, then the describe_failure method on Validator will be called.

None
value str | None

The value that was considered invalid. This is optional, and only needs to be supplied if required in your Input.Changed handler.

None
failures Failure | Sequence[Failure] | None

The reasons the validator failed. If not supplied, a generic Failure will be included in the ValidationResult returned from this function.

None
Returns
Type Description
ValidationResult

A ValidationResult representing failed validation, and containing the metadata supplied to this function.

success method

def success(self):

Shorthand for ValidationResult(True).

You can return success() from a Validator.validate method implementation to signal that validation has succeeded.

Returns
Type Description
ValidationResult

A ValidationResult indicating validation succeeded.

validate abstractmethod

def validate(self, value):

Validate the value and return a ValidationResult describing the outcome of the validation.

Parameters
Name Type Description Default
value str

The value to validate.

required
Returns
Type Description
ValidationResult

The result of the validation.