wtforms icon indicating copy to clipboard operation
wtforms copied to clipboard

implement DateRange validator similar to NumberRange

Open jkittner opened this issue 1 year ago • 0 comments

This adds a validator for date(-time) range similar to NumberRange

for DateField one could use:

DateRange(min=date(2023, 1, 1), max=date(2023, 12, 31))

for DateTimeLocalField one could use:

DateRange(min=datetime(2023, 1, 1, 00, 38), max=datetime(2023, 1, 1, 15, 54), input_type='datetime-local')

Both of the above set the min or max attribute to the input if possible

It also supports a server-side dynamic validation e.g. like this, where you can pass a callback function, that either returns a date or datetime respectively. This could allow for cases, where the date must not be in the past or must not be in the future, but relative to the current time.

from datetime import date
from datetime import datetime
from datetime import timedelta
from functools import partial

from wtforms import Form
from wtforms.fields import DateField
from wtforms.fields import DateTimeLocalField
from wtforms.validators import DateRange


def in_n_days(days):
    return datetime.now() + timedelta(days=days)


cb = partial(in_n_days, 5)


class DateForm(Form):
    date = DateField("date", [DateRange(min=date(2023, 1, 1), max_callback=cb)])
    datetime = DateTimeLocalField(
        "datetime-local",
        [
            DateRange(
                min=datetime(2023, 1, 1, 15, 30),
                max_callback=cb,
                input_type="datetime-local",
            )
        ],
  • I added tests validating the behavior
  • I added documentation with an example for the callbacks

jkittner avatar May 24 '23 17:05 jkittner