Commits

James Crasta committed 4b5753d

Implement ability for Optional to not strip input.

Comments (0)

Files changed (2)

tests/validators.py

     def test_optional(self):
         self.assertEqual(optional()(self.form, DummyField('foobar', raw_data=['foobar'])), None)
         self.assertRaises(StopValidation, optional(), self.form, DummyField('', raw_data=['']))
-        self.assertRaises(StopValidation, optional(), self.form, DummyField(' ', raw_data=[' ']))
         self.assertEqual(optional().field_flags, ('optional', ))
         f = DummyField('', ['Invalid Integer Value'], raw_data=[''])
         self.assertEqual(len(f.errors), 1)
         self.assertRaises(StopValidation, optional(), self.form, f)
         self.assertEqual(len(f.errors), 0)
 
+        # Test for whitespace behavior.
+        whitespace_field = DummyField(' ', raw_data=[' '])
+        self.assertRaises(StopValidation, optional(), self.form, whitespace_field)
+        self.assertEqual(optional(strip_whitespace=False)(self.form, whitespace_field), None)
+
     def test_regexp(self):
         import re
         # String regexp

wtforms/validators.py

 
     If input is empty, also removes prior errors (such as processing errors)
     from the field.
+
+    :param strip_whitespace:
+        If True (the default) also stop the validation chain on input which
+        consists of only whitespace.
     """
     field_flags = ('optional', )
 
+    def __init__(self, strip_whitespace=True):
+        if strip_whitespace:
+            self.string_check = lambda s: s.strip()
+        else:
+            self.string_check = lambda s: s
+
     def __call__(self, form, field):
-        if not field.raw_data or isinstance(field.raw_data[0], string_types) and not field.raw_data[0].strip():
+        if not field.raw_data or isinstance(field.raw_data[0], string_types) and not self.string_check(field.raw_data[0]):
             field.errors[:] = []
             raise StopValidation()