--- a/Allura/allura/lib/validators.py
+++ b/Allura/allura/lib/validators.py
@@ -3,6 +3,7 @@
import formencode as fe
from formencode import validators as fev
from . import helpers as h
+from datetime import datetime
class Ming(fev.FancyValidator):
@@ -61,3 +62,86 @@
except ValueError, e:
raise fe.Invalid('Invalid JSON: ' + str(e), value, state)
return value
+
+class DateValidator(fev.FancyValidator):
+ def _to_python(self, value, state):
+ value = convertDate(value)
+ if not value:
+ raise fe.Invalid(
+ "Please enter a valid date in the format DD/MM/YYYY.",
+ value, state)
+ return value
+
+class TimeValidator(fev.FancyValidator):
+ def _to_python(self, value, state):
+ value = convertTime(value)
+ if not value:
+ raise fe.Invalid(
+ "Please enter a valid time in the format HH:MM.",
+ value, state)
+ return value
+
+class OneOfValidator(fev.FancyValidator):
+ def __init__(self, validvalues, not_empty = True):
+ self.validvalues = validvalues
+ self.not_empty = not_empty
+ super(OneOfValidator, self).__init__()
+
+ def _to_python(self, value, state):
+ if not value.strip():
+ if self.not_empty:
+ raise fe.Invalid("This field can't be empty.", value, state)
+ else:
+ return None
+ if not value in self.validvalues:
+ allowed = ''
+ for v in self.validvalues:
+ if allowed != '':
+ allowed = allowed + ', '
+ allowed = allowed + '"%s"' % v
+ raise fe.Invalid(
+ "Invalid value. The allowed values are %s." %allowed,
+ value, state)
+ return value
+
+class MapValidator(fev.FancyValidator):
+ def __init__(self, mapvalues, not_empty = True):
+ self.map = mapvalues
+ self.not_empty = not_empty
+ super(MapValidator, self).__init__()
+
+ def _to_python(self, value, state):
+ if not value.strip():
+ if self.not_empty:
+ raise fe.Invalid("This field can't be empty.", value, state)
+ else:
+ return None
+ conv_value = self.map.get(value)
+ if not conv_value:
+ raise fe.Invalid(
+ "Invalid value. Please, choose one of the valid values.",
+ value, state)
+ return conv_value
+
+def convertDate(datestring):
+ formats = ['%Y-%m-%d', '%Y.%m.%d', '%Y/%m/%d', '%Y\%m\%d', '%Y %m %d',
+ '%d-%m-%Y', '%d.%m.%Y', '%d/%m/%Y', '%d\%m\%Y', '%d %m %Y']
+
+ for f in formats:
+ try:
+ date = datetime.strptime(datestring, f)
+ return date
+ except:
+ pass
+ return None
+
+def convertTime(timestring):
+ formats = ['%H:%M', '%H.%M', '%H %M', '%H,%M']
+
+ for f in formats:
+ try:
+ time = datetime.strptime(timestring, f)
+ return {'h':time.hour, 'm':time.minute}
+ except:
+ pass
+ return None