Permalink
Browse files

adding a DateTime field

  • Loading branch information...
1 parent 42cd1d7 commit 47026ce4c1b0652bd0fb2984250884ab2774dab2 @anemitz anemitz committed Oct 5, 2012
Showing with 29 additions and 0 deletions.
  1. +19 −0 cleancat/base.py
  2. +1 −0 requirements.txt
  3. +9 −0 tests/__init__.py
View
@@ -1,4 +1,7 @@
import re
+import datetime
+from dateutil import parser
+
class ValidationError(Exception):
pass
@@ -68,6 +71,22 @@ def clean(self, value):
return value
+class DateTime(Regex):
+ """ ISO 8601 from http://www.pelagodesign.com/blog/2009/05/20/iso-8601-date-validation-that-doesnt-suck/ """
+ regex = "^([\\+-]?\\d{4}(?!\\d{2}\\b))((-?)((0[1-9]|1[0-2])(\\3([12]\\d|0[1-9]|3[01]))?|W([0-4]\\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\\d|[12]\\d{2}|3([0-5]\\d|6[1-6])))([T\\s]((([01]\\d|2[0-3])((:?)[0-5]\\d)?|24\\:?00)([\\.,]\\d+(?!:))?)?(\\17[0-5]\\d([\\.,]\\d+)?)?([zZ]|([\\+-])([01]\\d|2[0-3]):?([0-5]\\d)?)?)?)?$"
+ regex_message = 'Invalid ISO 8601 datetime.'
+
+ def clean(self, value):
+ value = super(Regex, self).clean(value)
+ match = self.get_regex().match(value)
+ if not match:
+ raise ValidationError(self.regex_message)
+ dt = parser.parse(value)
+ time_group = match.groups()[11]
+ if time_group and len(time_group) > 1:
+ return dt
+ return dt.date()
+
class Email(Regex):
regex = r'^.+@[^.].*\.[a-z]{2,10}$'
regex_flags = re.IGNORECASE
View
@@ -0,0 +1 @@
+python-dateutil
View
@@ -1,4 +1,5 @@
import unittest
+import datetime
from cleancat import *
from cleancat.utils import ValidationTestCase
@@ -78,6 +79,14 @@ class OptionalRegexMessageSchema(Schema):
self.assertInvalid(schema, {'errors': ['letter']})
self.assertEqual(schema.errors['letter'], u'Not a lowercase letter.')
+ def test_datetime(self):
+ class DateTimeSchema(Schema):
+ dt = DateTime()
+
+ self.assertValid(DateTimeSchema({'dt': '2012-10-09'}), {'dt': datetime.date(2012,10,9)})
+ self.assertValid(DateTimeSchema({'dt': '2012-10-09 13:10:04'}), {'dt': datetime.datetime(2012,10,9, 13,10,04)})
+ self.assertInvalid(DateTimeSchema({'dt': '2012a'}), {'errors': ['dt']})
+
def test_email(self):
class EmailSchema(Schema):
email = Email(required=True)

0 comments on commit 47026ce

Please sign in to comment.