Validator

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

Parameters

Each prompt accepts two parameters for validation: validate and invalid_message.

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

Classic Syntax
from InquirerPy import prompt

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

result = inquirer.text(
    message="Name:",
    validate=lambda result: len(result) > 0,
    invalid_message="Input cannot be empty.",
).execute()

Below is another example which ensure that at least 2 options are checked.

Classic Syntax
from InquirerPy import prompt

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.",
        }
    ]
)
Alternate Syntax
from InquirerPy import inquirer

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

validate

Union[Callable[[Any], bool], "Validator"]

Validation callable or class to validate user input.

Callable

Note

The result provided will vary depending on the prompt types. E.g. checkbox prompt will receive a list of checked choices as the result.

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(result) -> bool:
    """Ensure the input is not empty."""
    return len(result) > 0

prompt_toolkit.validation.Validator

Note

To maintain API compatibility, for prompts that doesn’t have a string type result such as checkbox, you’ll still need to access the result via document.text.

You can also provide a prompt_toolkit Validator instance.

This method removes the need of providing the invalid_message parameter.

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

invalid_message

str

The error message you would like to display to user when the input is invalid.

Pre-built Validators

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

PathValidator

class InquirerPy.validator.PathValidator(message='Input is not a valid path', is_file=False, is_dir=False)[source]

Validator to validate if input is a valid filepath on the system.

Parameters
  • message (str) – Error message to display in the validatation toolbar when validation failed.

  • is_file (bool) – Explicitly check if the input is a valid file on the system.

  • is_dir (bool) – Explicitly check if the input is a valid directory/folder on the system.

Return type

None

Classic Syntax
from InquirerPy import prompt
from InquirerPy.validator import PathValidator

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

result = inquirer.filepath(message="Enter path:", validate=PathValidator()).execute()

EmptyInputValidator

class InquirerPy.validator.EmptyInputValidator(message='Input cannot be empty')[source]

Validator to validate if the input is empty.

Parameters

message (str) – Error message to display in the validatation toolbar when validation failed.

Return type

None

Classic Syntax
from InquirerPy import prompt
from InquirerPy.validator import EmptyInputValidator

result = prompt(
    [{"type": "input", "message": "Name:", "validate": EmptyInputValidator()}]
)
Alternate Syntax
from InquirerPy import inquirer
from InquirerPy.validator import EmptyInputValidator

result = inquirer.text(
    message="Name:", validate=EmptyInputValidator("Input should not be empty")
).execute()

PasswordValidator

class InquirerPy.validator.PasswordValidator(message='Input is not compliant with the password constraints', length=None, cap=False, special=False, number=False)[source]

Validator to validate password compliance.

Parameters
  • message (str) – Error message to display in the validatation toolbar when validation failed.

  • length (Optional[int]) – The minimum length of the password.

  • cap (bool) – Password should include at least one capital letter.

  • special (bool) – Password should include at least one special char “@$!%*#?&”.

  • number (bool) – Password should include at least one number.

Return type

None

Classic Syntax
from InquirerPy import prompt
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",
            ),
        }
    ]
)
Alternate Syntax
from InquirerPy import inquirer
from InquirerPy.validator import PasswordValidator

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

NumberValidator

class InquirerPy.validator.NumberValidator(message='Input should be a number', float_allowed=False)[source]

Validator to validate if input is a number.

Parameters
  • message (str) – Error message to display in the validatation toolbar when validation failed.

  • float_allowed (bool) – Allow input to contain floating number (with decimal).

Return type

None

Classic Syntax
from InquirerPy import prompt
from InquirerPy.validator import NumberValidator

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

result = inquirer.text(message="Age:", validate=NumberValidator()).execute()