Ticket #2674: dates.diff

File dates.diff, 2.1 KB (added by Gary Wilson <gary.wilson@…>, 9 years ago)
  • django/core/validators.py

     
    1313from django.utils.functional import Promise, lazy
    1414import re
    1515
    16 _datere = r'(19|2\d)\d{2}-((?:0?[1-9])|(?:1[0-2]))-((?:0?[1-9])|(?:[12][0-9])|(?:3[0-1]))'
     16_datere = r'\d{4}-\d{1,2}-\d{1,2}'
    1717_timere = r'(?:[01]?[0-9]|2[0-3]):[0-5][0-9](?::[0-5][0-9])?'
    1818alnum_re = re.compile(r'^\w+$')
    1919alnumurl_re = re.compile(r'^[-\w/]+$')
     
    122122    if not field_data.isalpha():
    123123        raise ValidationError, gettext("Only alphabetical characters are allowed here.")
    124124
     125def _isValidDate(date_string):
     126    """
     127    A helper function used by isValidANSIDate and isValidANSIDatetime to
     128    check if the date is valid.  The date string passed is assumed to
     129    already be in the correct YYYY-MM-DD format.
     130    """
     131    from datetime import date
     132    # Could use time.strptime here and catch errors, but datetime.date below
     133    # produces much friendlier error messages.
     134    year, month, day = map(int, date_string.split('-'))
     135    # This check is needed because strftime is used when saving the date
     136    # value to the database, and strftime requires that the year be >=1900.
     137    if year < 1900:
     138        raise ValidationError, gettext('Year must be 1900 or later.')
     139    try:
     140        date(year, month, day)
     141    except ValueError, e:
     142        raise ValidationError, gettext('Enter a valid date: %s.' % e)   
     143
    125144def isValidANSIDate(field_data, all_data):
    126145    if not ansi_date_re.search(field_data):
    127146        raise ValidationError, gettext('Enter a valid date in YYYY-MM-DD format.')
     147    _isValidDate(field_data)
    128148
    129149def isValidANSITime(field_data, all_data):
    130150    if not ansi_time_re.search(field_data):
     
    133153def isValidANSIDatetime(field_data, all_data):
    134154    if not ansi_datetime_re.search(field_data):
    135155        raise ValidationError, gettext('Enter a valid date/time in YYYY-MM-DD HH:MM format.')
     156    _isValidDate(field_data.split()[0])
    136157
    137158def isValidEmail(field_data, all_data):
    138159    if not email_re.search(field_data):
Back to Top