Python prompt_toolkit.validation.ValidationError() Examples

The following are 30 code examples of prompt_toolkit.validation.ValidationError(). 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: 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 #3
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 #4
Source File: interact.py    From plaid2text with GNU General Public License v3.0 6 votes vote down vote up
def validate(self, document):
        NullValidator.validate(self, document)
        text = document.text
        if self.allow_quit and text.lower() == 'q':
            return
        if not text.isdigit():
            i = 0
            for i, c in enumerate(text):
                if not c.isdigit():
                    break
            raise ValidationError(message=self.message, cursor_position=i)

        if not bool(self.max_number):
            return
        valid = int(text) <= int(self.max_number) and not int(text) == 0
        if not valid:
                range_message = 'You must enter a number between 1 and {}'.format(self.max_number)
                raise ValidationError(message=range_message) 
Example #5
Source File: test_io.py    From rasa-for-botfront with Apache License 2.0 6 votes vote down vote up
def test_create_validator_from_callable():
    def is_valid(user_input) -> None:
        return user_input == "this passes"

    error_message = "try again"

    validator = io_utils.create_validator(is_valid, error_message)

    document = Document("this passes")
    assert validator.validate(document) is None

    document = Document("this doesn't")
    with pytest.raises(ValidationError) as e:
        validator.validate(document)

    assert e.value.message == error_message 
Example #6
Source File: __main__.py    From chepy with GNU General Public License v3.0 6 votes vote down vote up
def validate(self, document):
        text = document.text.split()
        if re.search(r"^(!|#|\?)", document.text):
            pass
        elif len(text) > 1:
            if not text[-2].startswith("--"):
                if (
                    not re.search(r"\"|'", text[-1])
                    and not text[-1].startswith("--")
                    and text[-1] not in list(get_options().keys())
                ):
                    raise ValidationError(
                        cursor_position=1,
                        message="{text} is not a valid Chepy method".format(
                            text=text[-1]
                        ),
                    ) 
Example #7
Source File: config.py    From mlbstreamer with GNU General Public License v2.0 6 votes vote down vote up
def validate(self, document):

        text = document.text

        if not text:
            raise ValidationError(message="Please supply a value")

        if text.isdigit():
            value = int(text)
        else:
            i = 0

            raise ValidationError(
                message='Please enter an integer.'
            )

        if self.minimum and value < self.minimum:
            raise ValidationError(
                message="Value must be greater than %s" %(self.minimum)
            )

        if self.maximum and value > self.maximum:
            raise ValidationError(
                message="Value must be less than %s" %(self.maximum)
            ) 
Example #8
Source File: interact.py    From plaid2text with GNU General Public License v3.0 5 votes vote down vote up
def validate(self, document):
        text = document.text
        if not text:
            raise ValidationError(message=self.message)
        elif self.allow_quit and text.lower() == 'q':
            return 
Example #9
Source File: interactive.py    From st2 with Apache License 2.0 5 votes vote down vote up
def validate(input, spec):
        if not input and (not spec.get('required', None) or spec.get('default', None)):
            return

        if not input.isdigit():
            raise validation.ValidationError(len(input), 'Not a number')

        enum = spec.get('enum')
        try:
            enum[int(input)]
        except IndexError:
            raise validation.ValidationError(len(input), 'Out of bounds') 
Example #10
Source File: interactive.py    From st2 with Apache License 2.0 5 votes vote down vote up
def validate(input, spec):
        if not input and (not spec.get('required', None) or spec.get('default', None)):
            return

        for m in re.finditer(r'[^, ]+', input):
            index, item = m.start(), m.group()
            try:
                EnumReader.validate(item, spec.get('items', {}))
            except validation.ValidationError as e:
                raise validation.ValidationError(index, six.text_type(e)) 
Example #11
Source File: test_io.py    From rasa-for-botfront with Apache License 2.0 5 votes vote down vote up
def test_file_path_validator_with_invalid_paths(actual_path):
    test_error_message = actual_path

    validator = io_utils.file_type_validator([".yml"], test_error_message)

    document = Document(actual_path)
    with pytest.raises(ValidationError) as e:
        validator.validate(document)

    assert e.value.message == test_error_message 
Example #12
Source File: test_io.py    From rasa-for-botfront with Apache License 2.0 5 votes vote down vote up
def test_non_empty_text_validator_with_empty_input(user_input):
    test_error_message = "enter something"

    validator = io_utils.not_empty_validator(test_error_message)

    document = Document(user_input)
    with pytest.raises(ValidationError) as e:
        validator.validate(document)

    assert e.value.message == test_error_message 
Example #13
Source File: interact.py    From plaid2text with GNU General Public License v3.0 5 votes vote down vote up
def validate(self, document):
        text = document.text.lower()
        # Assumes that there is a default for empty
        if not bool(text):
            return
        if not (text.startswith('y') or text.startswith('n')):
            raise ValidationError(message='Please enter y[es] or n[o]') 
Example #14
Source File: interactive.py    From st2 with Apache License 2.0 5 votes vote down vote up
def validate(input, spec):
        if not input and (not spec.get('required', None) or spec.get('default', None)):
            return

        if input.lower() not in POSITIVE_BOOLEAN | NEGATIVE_BOOLEAN:
            raise validation.ValidationError(len(input),
                                             'Does not look like boolean. Pick from [%s]'
                                             % ', '.join(POSITIVE_BOOLEAN | NEGATIVE_BOOLEAN)) 
Example #15
Source File: interact.py    From plaid2text with GNU General Public License v3.0 5 votes vote down vote up
def validate(self, document):
        NumberValidator.validate(self, document)
        text = document.text
        if self.allow_quit and text.lower() == 'q':
            return
        text_length = len(text)
        if not text_length >= self.min_number:
            raise ValidationError(message=self.message, cursor_position=text_length) 
Example #16
Source File: prompt.py    From aq with MIT License 5 votes vote down vote up
def validate(self, document):
        try:
            self.parser.parse_query(document.text)
        except QueryParsingError as e:
            raise ValidationError(message='Invalid SQL query. {0}'.format(e),
                                  cursor_position=document.cursor_position) 
Example #17
Source File: validation.py    From android_universal with MIT License 5 votes vote down vote up
def validate(self, document):
        # Parse input document.
        # We use `match`, not `match_prefix`, because for validation, we want
        # the actual, unambiguous interpretation of the input.
        m = self.compiled_grammar.match(document.text)

        if m:
            for v in m.variables():
                validator = self.validators.get(v.varname)

                if validator:
                    # Unescape text.
                    unwrapped_text = self.compiled_grammar.unescape(v.varname, v.value)

                    # Create a document, for the completions API (text/cursor_position)
                    inner_document = Document(unwrapped_text, len(unwrapped_text))

                    try:
                        validator.validate(inner_document)
                    except ValidationError as e:
                        raise ValidationError(
                            cursor_position=v.start + e.cursor_position,
                            message=e.message)
        else:
            raise ValidationError(cursor_position=len(document.text),
                                  message='Invalid command') 
Example #18
Source File: base.py    From android_universal with MIT License 5 votes vote down vote up
def validate(self, document):
        if document.text not in self.sentences:
            if self.move_cursor_to_end:
                index = len(document.text)
            else:
                index = 0

            raise ValidationError(cursor_position=index,
                                  message=self.error_message) 
Example #19
Source File: validator.py    From python-sploitkit with GNU Affero General Public License v3.0 5 votes vote down vote up
def validate(self, document):
        # first, tokenize document.text
        tokens = self.console._get_tokens(document.text.strip())
        l = len(tokens)
        # then handle tokens
        commands = self.console.commands
        # when no token provided, do nothing
        if l == 0:
            return
        # when a command is being typed, mention if it is existing
        cmd = tokens[0]
        if l == 1 and cmd not in commands.keys():
            raise ValidationError(message="Unknown command")
        # when a valid first token is provided, handle command's validation, if
        #  any available
        elif l >= 1 and cmd in commands.keys():
            c = commands[cmd]._instance
            try:
                c._validate(*tokens[1:])
            except Exception as e:
                m = "Command syntax: %s{}" % c.signature.format(cmd)
                e = str(e)
                if not e.startswith("validate() "):
                    m = m.format([" (" + e + ")", ""][len(e) == 0])
                else:
                    m = m.format("")
                raise ValidationError(message=m)
        # otherwise, the command is considered bad
        else:
            raise ValidationError(message="Bad command") 
Example #20
Source File: interactive.py    From st2 with Apache License 2.0 5 votes vote down vote up
def validate(input, spec):
        if input:
            try:
                input = int(input)
            except ValueError as e:
                raise validation.ValidationError(len(input), six.text_type(e))

            super(IntegerReader, IntegerReader).validate(input, spec) 
Example #21
Source File: validators.py    From maubot with GNU Affero General Public License v3.0 5 votes vote down vote up
def validate(self, document: Document) -> None:
        if len(document.text) == 0:
            raise ValidationError(message="This field is required")
        if self.proxy:
            return self.proxy.validate(document) 
Example #22
Source File: interactive.py    From st2 with Apache License 2.0 5 votes vote down vote up
def validate(input, spec):
        try:
            jsonschema.validate(input, spec, Draft3Validator)
        except jsonschema.ValidationError as e:
            raise validation.ValidationError(len(input), six.text_type(e)) 
Example #23
Source File: validation.py    From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def validate(self, document: Document) -> None:
        # Parse input document.
        # We use `match`, not `match_prefix`, because for validation, we want
        # the actual, unambiguous interpretation of the input.
        m = self.compiled_grammar.match(document.text)

        if m:
            for v in m.variables():
                validator = self.validators.get(v.varname)

                if validator:
                    # Unescape text.
                    unwrapped_text = self.compiled_grammar.unescape(v.varname, v.value)

                    # Create a document, for the completions API (text/cursor_position)
                    inner_document = Document(unwrapped_text, len(unwrapped_text))

                    try:
                        validator.validate(inner_document)
                    except ValidationError as e:
                        raise ValidationError(
                            cursor_position=v.start + e.cursor_position,
                            message=e.message,
                        ) from e
        else:
            raise ValidationError(
                cursor_position=len(document.text), message="Invalid command"
            ) 
Example #24
Source File: interactive_release.py    From releases with Apache License 2.0 5 votes vote down vote up
def validate(self, document):
        text = document.text
        if text not in self.allowed_values:
            if self.show_possible:
                raise ValidationError(
                    message='This input is not allowed, '
                            ' please choose from %s' % self.allowed_values)
            else:
                raise ValidationError(
                    message='This input is not allowed') 
Example #25
Source File: interactive_release.py    From releases with Apache License 2.0 5 votes vote down vote up
def validate(self, document):
        text = document.text.strip()
        if len(text) == 0:
            raise ValidationError(message='Empty input is not allowed') 
Example #26
Source File: config.py    From mlbstreamer with GNU General Public License v2.0 5 votes vote down vote up
def validate(self, document):
        text = document.text
        if not len(text):
            raise ValidationError(message="Please supply a value") 
Example #27
Source File: validator.py    From ptpython with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def validate(self, document):
        """
        Check input for Python syntax errors.
        """
        # When the input starts with Ctrl-Z, always accept. This means EOF in a
        # Python REPL.
        if document.text.startswith("\x1a"):
            return

        try:
            if self.get_compiler_flags:
                flags = self.get_compiler_flags()
            else:
                flags = 0

            compile(document.text, "<input>", "exec", flags=flags, dont_inherit=True)
        except SyntaxError as e:
            # Note, the 'or 1' for offset is required because Python 2.7
            # gives `None` as offset in case of '4=4' as input. (Looks like
            # fixed in Python 3.)
            index = document.translate_row_col_to_index(
                e.lineno - 1, (e.offset or 1) - 1
            )
            raise ValidationError(index, "Syntax Error")
        except TypeError as e:
            # e.g. "compile() expected string without null bytes"
            raise ValidationError(0, str(e))
        except ValueError as e:
            # In Python 2, compiling "\x9" (an invalid escape sequence) raises
            # ValueError instead of SyntaxError.
            raise ValidationError(0, "Syntax Error: %s" % e) 
Example #28
Source File: common.py    From PyInquirer with MIT License 5 votes vote down vote up
def setup_simple_validator(kwargs):
    # this is an internal helper not meant for public consumption!
    # note this works on a dictionary
    # this validates the answer not a buffer
    # TODO
    # not sure yet how to deal with the validation result:
    # https://github.com/jonathanslenders/python-prompt-toolkit/issues/430
    validate = kwargs.pop('validate', None)
    if validate is None:
        def _always(answer):
            return True
        return _always
    elif not callable(validate):
        raise ValueError('Here a simple validate function is expected, no class')

    def _validator(answer):
        verdict = validate(answer)
        if isinstance(verdict, basestring):
            raise ValidationError(
                message=verdict
                )
        elif verdict is not True:
            raise ValidationError(
                message='invalid input'
                )
    return _validator


# FIXME style defaults on detail level 
Example #29
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 #30
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"