• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

LeanderCS / flask-inputfilter / #389

24 May 2025 01:01PM UTC coverage: 93.409% (-0.2%) from 93.644%
#389

Pull #56

coveralls-python

LeanderCS
48 | Remove typing_extensions dep
Pull Request #56: 48 | Update ArrayElementValidator and IsDataclassValidator

64 of 73 new or added lines in 4 files covered. (87.67%)

87 existing lines in 18 files now uncovered.

1885 of 2018 relevant lines covered (93.41%)

0.93 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

89.29
/flask_inputfilter/validators/date_range_validator.py
1
from __future__ import annotations
1✔
2

3
from datetime import date, datetime
1✔
4
from typing import Any, Optional, Union
1✔
5

6
from flask_inputfilter.exceptions import ValidationError
1✔
7
from flask_inputfilter.validators import BaseValidator
1✔
8

9

10
class DateRangeValidator(BaseValidator):
1✔
11
    """
12
    Checks if a date falls within a specified range.
13

14
    **Parameters:**
15

16
    - **min_date** (*Optional[Union[str, date, datetime]]*): The lower bound of the date range.
17
    - **max_date** (*Optional[Union[str, date, datetime]]*): The upper bound of the date range.
18
    - **error_message** (*Optional[str]*): Custom error message if the date is outside the range.
19

20
    **Expected Behavior:**
21

22
    Ensures the input date is not earlier than ``min_date`` and not later than ``max_date``. A ``ValidationError`` is raised if the check fails.
23

24
    **Example Usage:**
25

26
    .. code-block:: python
27

28
        class BookingInputFilter(InputFilter):
29
            def __init__(self):
30
                super().__init__()
31

32
                self.add('booking_date', validators=[
33
                    DateRangeValidator(
34
                        min_date="2023-01-01",
35
                        max_date="2023-12-31"
36
                    )
37
                ])
38
    """
39

40
    __slots__ = ("min_date", "max_date", "error_message")
1✔
41

42
    def __init__(
1✔
43
        self,
44
        min_date: Optional[Union[str, date, datetime]] = None,
45
        max_date: Optional[Union[str, date, datetime]] = None,
46
        error_message: Optional[str] = None,
47
    ) -> None:
48
        self.min_date = min_date
1✔
49
        self.max_date = max_date
1✔
50
        self.error_message = error_message
1✔
51

52
    def validate(self, value: Any) -> None:
1✔
53
        value_date = self.__parse_date(value)
1✔
54
        min_date = self.__parse_date(self.min_date) if self.min_date else None
1✔
55
        max_date = self.__parse_date(self.max_date) if self.max_date else None
1✔
56

57
        if (min_date and value_date < min_date) or (
1✔
58
            max_date and value_date > max_date
59
        ):
60
            raise ValidationError(
1✔
61
                self.error_message
62
                or f"Date '{value}' is not in the range from "
63
                f"'{self.min_date}' to '{self.max_date}'."
64
            )
65

66
    @staticmethod
1✔
67
    def __parse_date(value: Any) -> datetime:
68
        """
69
        Converts a value to a datetime object.
70

71
        Supports ISO 8601 formatted strings and datetime objects.
72
        """
73

74
        if isinstance(value, datetime):
1✔
75
            return value
1✔
76

77
        elif isinstance(value, str):
1✔
78
            try:
1✔
79
                return datetime.fromisoformat(value)
1✔
80

UNCOV
81
            except ValueError:
×
UNCOV
82
                raise ValidationError(f"Invalid ISO 8601 format '{value}'.")
×
83

84
        elif isinstance(value, date):
1✔
85
            return datetime.combine(value, datetime.min.time())
1✔
86

UNCOV
87
        raise ValidationError(
×
88
            f"Unsupported type for past date validation '{type(value)}'."
89
        )
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc