validation.py 1.7 KB

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