Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/validators/length.py: 82%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

11 statements  

1"""Length.""" 

2 

3# standard 

4from typing import Union 

5 

6# local 

7from .between import between 

8from .utils import validator 

9 

10 

11@validator 

12def length(value: str, /, *, min_val: Union[int, None] = None, max_val: Union[int, None] = None): 

13 """Return whether or not the length of given string is within a specified range. 

14 

15 Examples: 

16 >>> length('something', min_val=2) 

17 True 

18 >>> length('something', min_val=9, max_val=9) 

19 True 

20 >>> length('something', max_val=5) 

21 ValidationError(func=length, args={'value': 'something', 'max_val': 5}) 

22 

23 Args: 

24 value: 

25 The string to validate. 

26 min_val: 

27 The minimum required length of the string. If not provided, 

28 minimum length will not be checked. 

29 max_val: 

30 The maximum length of the string. If not provided, 

31 maximum length will not be checked. 

32 

33 Returns: 

34 (Literal[True]): If `len(value)` is in between the given conditions. 

35 (ValidationError): If `len(value)` is not in between the given conditions. 

36 

37 Raises: 

38 (ValueError): If either `min_val` or `max_val` is negative. 

39 """ 

40 if min_val is not None and min_val < 0: 

41 raise ValueError("Length cannot be negative. `min_val` is less than zero.") 

42 if max_val is not None and max_val < 0: 

43 raise ValueError("Length cannot be negative. `max_val` is less than zero.") 

44 

45 return bool(between(len(value), min_val=min_val, max_val=max_val))