Python prompt_toolkit.validation.Validator() Examples

The following are 10 code examples of prompt_toolkit.validation.Validator(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module prompt_toolkit.validation , or try the search function .
Example #1
Source File: common.py    From questionary with MIT License 6 votes vote down vote up
def build_validator(validate: Any) -> Optional[Validator]:
    if validate:
        if inspect.isclass(validate) and issubclass(validate, Validator):
            return validate()
        elif isinstance(validate, Validator):
            return validate
        elif callable(validate):

            class _InputValidator(Validator):
                def validate(self, document):
                    verdict = validate(document.text)
                    if verdict is not True:
                        if verdict is False:
                            verdict = "invalid input"
                        raise ValidationError(
                            message=verdict, cursor_position=len(document.text)
                        )

            return _InputValidator()
    return None 
Example #2
Source File: common.py    From PyInquirer with MIT License 6 votes vote down vote up
def setup_validator(kwargs):
    # this is an internal helper not meant for public consumption!
    # note this works on a dictionary
    validate_prompt = kwargs.pop('validate', None)
    if validate_prompt:
        if issubclass(validate_prompt, Validator):
            kwargs['validator'] = validate_prompt()
        elif callable(validate_prompt):
            class _InputValidator(Validator):
                def validate(self, document):
                    #print('validation!!')
                    verdict = validate_prompt(document.text)
                    if isinstance(verdict, basestring):
                        raise ValidationError(
                            message=verdict,
                            cursor_position=len(document.text))
                    elif verdict is not True:
                        raise ValidationError(
                            message='invalid input',
                            cursor_position=len(document.text))
            kwargs['validator'] = _InputValidator()
        return kwargs['validator'] 
Example #3
Source File: io.py    From rasa-for-botfront with Apache License 2.0 6 votes vote down vote up
def create_validator(
    function: Callable[[Text], bool], error_message: Text
) -> Type["Validator"]:
    """Helper method to create `Validator` classes from callable functions. Should be
    removed when questionary supports `Validator` objects."""

    from prompt_toolkit.validation import Validator, ValidationError
    from prompt_toolkit.document import Document

    class FunctionValidator(Validator):
        @staticmethod
        def validate(document: Document) -> None:
            is_valid = function(document.text)
            if not is_valid:
                raise ValidationError(message=error_message)

    return FunctionValidator 
Example #4
Source File: cliq.py    From maubot with GNU Affero General Public License v3.0 5 votes vote down vote up
def option(short: str, long: str, message: str = None, help: str = None,
           click_type: Union[str, Callable[[str], Any]] = None, inq_type: str = None,
           validator: Validator = None, required: bool = False, default: str = None,
           is_flag: bool = False, prompt: bool = True) -> Callable[[Callable], Callable]:
    if not message:
        message = long[2].upper() + long[3:]
    click_type = validator.click_type if isinstance(validator, ClickValidator) else click_type
    if is_flag:
        click_type = yesno

    def decorator(func) -> Callable:
        click.option(short, long, help=help, type=click_type)(func)
        if not prompt:
            return func
        if not hasattr(func, "__inquirer_questions__"):
            func.__inquirer_questions__ = {}
        q = {
            "type": (inq_type if isinstance(inq_type, str)
                     else ("input" if not is_flag
                           else "confirm")),
            "name": long[2:],
            "message": message,
        }
        if default is not None:
            q["default"] = default
        if required:
            q["validator"] = Required(validator)
        elif validator:
            q["validator"] = validator
        func.__inquirer_questions__[long[2:]] = q
        return func

    return decorator 
Example #5
Source File: validators.py    From maubot with GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, proxy: Validator = None) -> None:
        self.proxy = proxy 
Example #6
Source File: test_text.py    From questionary with MIT License 5 votes vote down vote up
def test_text_validate_with_class():
    class SimpleValidator(Validator):
        def validate(self, document):
            ok = re.match("[01][01][01]", document.text)
            if not ok:
                raise ValidationError(
                    message="Binary FTW", cursor_position=len(document.text)
                )

    message = "What is your name"
    text = "001\r"

    result, cli = feed_cli_with_input("text", message, text, validate=SimpleValidator)
    assert result == "001" 
Example #7
Source File: input.py    From PyInquirer with MIT License 5 votes vote down vote up
def question(message, **kwargs):
    default = kwargs.pop('default', '')
    validate_prompt = kwargs.pop('validate', None)
    if validate_prompt:
        if inspect.isclass(validate_prompt) and issubclass(validate_prompt, Validator):
            kwargs['validator'] = validate_prompt()
        elif callable(validate_prompt):
            class _InputValidator(Validator):
                def validate(self, document):
                    verdict = validate_prompt(document.text)
                    if not verdict == True:
                        if verdict == False:
                            verdict = 'invalid input'
                        raise ValidationError(
                            message=verdict,
                            cursor_position=len(document.text))
            kwargs['validator'] = _InputValidator()

    # TODO style defaults on detail level
    kwargs['style'] = kwargs.pop('style', default_style)
    qmark = kwargs.pop('qmark', '?')


    def _get_prompt_tokens(cli):
        return [
            (Token.QuestionMark, qmark),
            (Token.Question, ' %s  ' % message)
        ]

    return create_prompt_application(
        get_prompt_tokens=_get_prompt_tokens,
        lexer=SimpleLexer(Token.Answer),
        default=default,
        **kwargs
    ) 
Example #8
Source File: validation.py    From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(
        self, compiled_grammar: _CompiledGrammar, validators: Dict[str, Validator]
    ) -> None:

        self.compiled_grammar = compiled_grammar
        self.validators = validators 
Example #9
Source File: io.py    From rasa-for-botfront with Apache License 2.0 5 votes vote down vote up
def file_type_validator(
    valid_file_types: List[Text], error_message: Text
) -> Type["Validator"]:
    """Creates a `Validator` class which can be used with `questionary` to validate
       file paths.
    """

    def is_valid(path: Text) -> bool:
        return path is not None and any(
            [path.endswith(file_type) for file_type in valid_file_types]
        )

    return create_validator(is_valid, error_message) 
Example #10
Source File: io.py    From rasa-for-botfront with Apache License 2.0 5 votes vote down vote up
def not_empty_validator(error_message: Text) -> Type["Validator"]:
    """Creates a `Validator` class which can be used with `questionary` to validate
    that the user entered something other than whitespace.
    """

    def is_valid(input: Text) -> bool:
        return input is not None and input.strip() != ""

    return create_validator(is_valid, error_message)