Code

Ticket #2674: dates.diff

File dates.diff, 2.1 KB (added by Gary Wilson <gary.wilson@…>, 8 years ago)
Line 
1Index: django/core/validators.py
2===================================================================
3--- django/core/validators.py   (revision 3689)
4+++ django/core/validators.py   (working copy)
5@@ -13,7 +13,7 @@
6 from django.utils.functional import Promise, lazy
7 import re
8 
9-_datere = r'(19|2\d)\d{2}-((?:0?[1-9])|(?:1[0-2]))-((?:0?[1-9])|(?:[12][0-9])|(?:3[0-1]))'
10+_datere = r'\d{4}-\d{1,2}-\d{1,2}'
11 _timere = r'(?:[01]?[0-9]|2[0-3]):[0-5][0-9](?::[0-5][0-9])?'
12 alnum_re = re.compile(r'^\w+$')
13 alnumurl_re = re.compile(r'^[-\w/]+$')
14@@ -122,9 +122,29 @@
15     if not field_data.isalpha():
16         raise ValidationError, gettext("Only alphabetical characters are allowed here.")
17 
18+def _isValidDate(date_string):
19+    """
20+    A helper function used by isValidANSIDate and isValidANSIDatetime to
21+    check if the date is valid.  The date string passed is assumed to
22+    already be in the correct YYYY-MM-DD format.
23+    """
24+    from datetime import date
25+    # Could use time.strptime here and catch errors, but datetime.date below
26+    # produces much friendlier error messages.
27+    year, month, day = map(int, date_string.split('-'))
28+    # This check is needed because strftime is used when saving the date
29+    # value to the database, and strftime requires that the year be >=1900.
30+    if year < 1900:
31+        raise ValidationError, gettext('Year must be 1900 or later.')
32+    try:
33+        date(year, month, day)
34+    except ValueError, e:
35+        raise ValidationError, gettext('Enter a valid date: %s.' % e)   
36+
37 def isValidANSIDate(field_data, all_data):
38     if not ansi_date_re.search(field_data):
39         raise ValidationError, gettext('Enter a valid date in YYYY-MM-DD format.')
40+    _isValidDate(field_data)
41 
42 def isValidANSITime(field_data, all_data):
43     if not ansi_time_re.search(field_data):
44@@ -133,6 +153,7 @@
45 def isValidANSIDatetime(field_data, all_data):
46     if not ansi_datetime_re.search(field_data):
47         raise ValidationError, gettext('Enter a valid date/time in YYYY-MM-DD HH:MM format.')
48+    _isValidDate(field_data.split()[0])
49 
50 def isValidEmail(field_data, all_data):
51     if not email_re.search(field_data):