Skip to content

Validator

Kevin Zhuang edited this page Jan 9, 2021 · 9 revisions

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 Validator

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())

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()

PasswordValidator

A Validator class to check password compliance.