aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/python/prompt-toolkit/py2/prompt_toolkit/validation.py
blob: f898796e066f43b967502524477a9567ba3e309c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
""" 
Input validation for a `Buffer`. 
(Validators will be called before accepting input.) 
""" 
from __future__ import unicode_literals 
from .filters import to_simple_filter 
 
from abc import ABCMeta, abstractmethod 
from six import with_metaclass 
 
__all__ = ( 
    'ConditionalValidator', 
    'ValidationError', 
    'Validator', 
) 
 
 
class ValidationError(Exception): 
    """ 
    Error raised by :meth:`.Validator.validate`. 
 
    :param cursor_position: The cursor position where the error occured. 
    :param message: Text. 
    """ 
    def __init__(self, cursor_position=0, message=''): 
        super(ValidationError, self).__init__(message) 
        self.cursor_position = cursor_position 
        self.message = message 
 
    def __repr__(self): 
        return '%s(cursor_position=%r, message=%r)' % ( 
            self.__class__.__name__, self.cursor_position, self.message) 
 
 
class Validator(with_metaclass(ABCMeta, object)): 
    """ 
    Abstract base class for an input validator. 
    """ 
    @abstractmethod 
    def validate(self, document): 
        """ 
        Validate the input. 
        If invalid, this should raise a :class:`.ValidationError`. 
 
        :param document: :class:`~prompt_toolkit.document.Document` instance. 
        """ 
        pass 
 
 
class ConditionalValidator(Validator): 
    """ 
    Validator that can be switched on/off according to 
    a filter. (This wraps around another validator.) 
    """ 
    def __init__(self, validator, filter): 
        assert isinstance(validator, Validator) 
 
        self.validator = validator 
        self.filter = to_simple_filter(filter)
 
    def validate(self, document): 
        # Call the validator only if the filter is active. 
        if self.filter(): 
            self.validator.validate(document)