Skip to content

Conversation

@jkittner
Copy link

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

@azmeuk azmeuk added the enhancement New feature, or existing feature improvement label Jul 22, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature, or existing feature improvement

Development

Successfully merging this pull request may close these issues.

2 participants