Skip to content

Validator

Kevin Zhuang edited this page Oct 5, 2021 · 9 revisions

This page is deprecated, documentation moved to: https://inquirerpy.readthedocs.io/

All InquirerPy prompts accepts Validator to validate user input and display an error toolbar when the input or selection is invalid.

The validate Parameter

All prompts accepts a validate parameter which can be either a callable or a prompt_toolkit Validator instance.

Below is an example of ensuring the user doesn't by pass an empty input.

from InquirerPy import prompt
from InquirerPy import inquirer

result = prompt(
    [
        {
            "type": "input",
            "message": "Name:",
            "validate": lambda text: len(text) > 0,
            "invalid_message": "Input cannot be empty.",
        }
    ]
)
result = inquirer.text(
    message="Name:",
    validate=lambda text: len(text) > 0,
    invalid_message="Input cannot be empty.",
).execute()

validate: Union[Callable[[str], bool], Validator]

When providing validate as a callable, it will be provided with the current user input and should return a boolean indicating if the input is valid.

def validator(text: str) -> bool:
    """Ensure the input is not empty."""
    return len(text) > 0

Invalid Message

To configure the invalid message, you can provide through parameter invalid_message, this parameter is present in all prompts. Check out the example in previous section.

Validator

You can also provide a prompt_toolkit Validator instance. For more information, please visit its documentation.

This method remove the need of providing the invalid_message parameter, but its a bit more lengthy and harder to use.

from prompt_toolkit.validation import ValidationError, Validator

class EmptyInputValidator(Validator):
    def validate(self, document):
        if not len(document.text) > 0:
            raise ValidationError(
                message="Input cannot be empty.",
                cursor_position=document.cursor_position,
            )

List Type Prompt

There may be several reasons you wanna validate the input of a list type of prompt such as a checkbox. Using the validate parameter you can insert validation such as forcing at least X amount of checkbox is ticked or check if user didn't tick anything.

Callable validate

To maintain API compatiblility, the callable validate parameter still accept a parameter, but depending on whether the prompt includes multiselect, the provided value maybe a list.

from InquirerPy import prompt
from InquirerPy import inquirer

result = prompt(
    [
        {
            "type": "list",
            "message": "Select toppings:",
            "choices": ["Bacon", "Chicken", "Cheese", "Pineapple"],
            "multiselect": True,
            "validate": lambda selection: len(selection) >= 2,
            "invalid_message": "Select at least 2 toppings.",
        }
    ]
)
result = inquirer.checkbox(
    message="Select toppings:",
    choices=["Bacon", "Chicken", "Cheese", "Pineapple"],
    validate=lambda selection: len(selection) >= 2,
    invalid_message="Select at least 2 toppings.",
).execute()

Validator validate

To maintain API compatiblility, the Validator instance validate would still be required to get the user input via document.text even if its a multiselect prompt or checkbox prompt when the input is an array.

from InquirerPy import prompt
from InquirerPy import inquirer
from prompt_toolkit.validation import ValidationError, Validator

class EmptyInputValidator(Validator):
    def validate(self, document):
        if not len(document.text) > 2:
            raise ValidationError(
                message="Select at least 2 toppings.",
                cursor_position=document.cursor_position,
            )

result = inquirer.checkbox(
    message="Select toppings:",
    choices=["Bacon", "Chicken", "Cheese", "Pineapple"],
    validate=EmptyInputValidator(),
    invalid_message="Select at least 2 toppings.",
).execute()

Pre-built Validators

There's a few pre-built common validator ready to use.

PathValidator

A Validator class to validate if user input path is an existing/valid path.

from InquirerPy import prompt
from InquirerPy import inquirer
from InquirerPy.validator import PathValidator

result = prompt(
    [
        {
            "type": "filepath",
            "message": "Enter path:",
            "validate": PathValidator("Path is not valid"),
        }
    ]
)
result = inquirer.filepath(message="Enter path:", validate=PathValidator())

message: str

The invalid message to display.

is_file: bool

Check if the input is an existing file.

is_dir: bool

Check if the input is an existing directory.

EmptyInputValidator

A Validator class to validate empty input.

from InquirerPy import prompt
from InquirerPy import inquirer
from InquirerPy.validator import EmptyInputValidator

result = prompt(
    [{"type": "input", "message": "Name:", "validate": EmptyInputValidator()}]
)
result = inquirer.text(
    message="Name:", validate=EmptyInputValidator("Input should not be empty")
).execute()

message: str

The invalid message to display.

PasswordValidator

A Validator class to check password compliance.

from InquirerPy import prompt
from InquirerPy import inquirer
from InquirerPy.validator import PasswordValidator

result = prompt(
    [
        {
            "type": "secret",
            "message": "New Password:",
            "validate": PasswordValidator(
                length=8,
                cap=True,
                special=True,
                number=True,
                message="Password does not meet compliance",
            ),
        }
    ]
)
result = inquirer.secret(
    message="New Password:",
    validate=PasswordValidator(
        length=8,
        cap=True,
        special=True,
        number=True,
        message="Password does not meet compliance",
    ),
).execute()

length: int

Specify minimum password length.

cap: bool

Include at least a capital character.

special: bool

Include at least a special character (@$!%*#?&).

number: bool

Include at least a number

message: str

The invalid message to display.

NumberValidator

A Validator class to validate if input is a number.

from InquirerPy import prompt
from InquirerPy import inquirer
from InquirerPy.validator import NumberValidator

result = prompt(
    [
        {
            "type": "text",
            "message": "Age:",
            "validate": NumberValidator(
                message="Input should be number", float_allowed=False
            ),
        }
    ]
)
result = inquirer.text(message="Age:", validate=NumberValidator())

message: str

The invalid message to display.

float_allowed: bool

Allow float number if True, otherwise only integer is allowed.