1
"""Custom validators for :mod:`attrs`."""
2

3 4
from attr.validators import instance_of
4

5

6 4
def str_of_length(length):
7
    """Validate that the value is a string of the given length."""
8

9 4
    def validator(instance, attribute, value):
10 4
        instance_of(str)(instance, attribute, value)
11 4
        if len(value) != length:
12 4
            raise ValueError(
13
                '{0.name} must be exactly {1} chars, got {2!r}'.format(
14
                    attribute, length, value
15
                )
16
            )
17

18 4
    return validator
19

20

21 4
def str_of_max_length(length):
22
    """Validate that the value is a string with a max length."""
23

24 4
    def validator(instance, attribute, value):
25 4
        instance_of(str)(instance, attribute, value)
26 4
        if len(value) > length:
27 4
            raise ValueError(
28
                '{0.name} must be at most {1} chars, '
29
                'got {2!r} which is {3} chars'.format(
30
                    attribute, length, value, len(value)
31
                )
32
            )
33

34 4
    return validator

Read our documentation on viewing source code .

Loading