Skip to content

Validation

We recommend to use the dataclass and validate with the Annotated keyword. We use a Validation type here.

from typing import Annotated
from mininterface.validators import not_empty
from mininterface import Validation

@dataclass
class Env:
    test: Annotated[str, Validation(not_empty)] = "hello"

Under the hood, this is just a Tag.

@dataclass
class Env:
    test: Annotated[str, Tag(validation=not_empty)] = "hello"

Why we used it in an Annotated statement? To preserve the date type.

@dataclass
class Env:
    my_string: Tag = Tag("hello", validation=not_empty)

m = run(Env)
print(type(m.env.my_string))  # Tag
print(m.env.my_string.val)  # hello

validators

Functions suitable for Tag validation. When the user submits a value whose validation fails, they are prompted to edit the value.

m = run()
my_dict = m.form({"my_text", Tag("", validation=validators.not_empty)})
my_dict["my_text"]  # You can be sure the value is not empty here.

Note that alternatively to this module, you may validate with Pydantic or an attrs model.

from pydantic import BaseModel, Field

class MyModel(BaseModel):
    restrained: str = Field(default="hello", max_length=5)
import attr
from attr.validators import max_len

@attr.s
class AttrsModel:
    restrained: str = attr.ib(default="hello", validator=max_len(5))

not_empty(tag)

Assures that Tag the user has written a value and did not let the field empty.

from mininterface import Tag, validators, run

m = run()
m.form({"my_text": Tag("", validation=validators.not_empty)})
# User cannot leave the string field empty.

When submitting an empty value, a warning appears:

Not empty window

Note that for Path, an empty string is converted to an empty Path('.'), hence '.' too is considered as an empty input and the user is not able to set '.' as a value. This does not seem to me as a bad behaviour as in CLI you clearly see the CWD, whereas in a UI the CWD is not evident.

Parameters:

Name Type Description Default
tag Tag
required

limit(maxOrMin=None, max_=None, lt=None, gt=None, transform=False)

Limit a number range or a string length.

Either use as limit(maximum) or limit(minimum, maximum).

Parameters:

Name Type Description Default
maximum int

limit(maximum) – from zero (including) to maximum (including)

required
minimum int

limit(minimum, maximum) – From minimum (including) to maximum (including)

required
lt float | None

lesser than

None
gt float | None

greater than

None
transform bool

If the value is not within the limit, transform it to a boundary.

from mininterface import run, Tag
from mininterface.validators import limit

m = run()
m.form({"my_number": Tag(2, validation=limit(1, 10, transform=True))})
# Put there '50' → transformed to 10 and dialog reappears
# with 'Value must be between 1 and 10.'

Validator limit

False