Skip to content

Commit

Permalink
Fixes #12
Browse files Browse the repository at this point in the history
  • Loading branch information
di committed Nov 20, 2015
1 parent bfce112 commit 776f054
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 2 deletions.
4 changes: 4 additions & 0 deletions vladiate/test/test_validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,10 @@ def test_regex_validator_works(pattern, field):
RegexValidator(pattern).validate(field)


def test_regex_validator_allows_empty():
RegexValidator(r'foo.*', empty_ok=True).validate('')


@pytest.mark.parametrize('pattern, field', [
(r'foo.*', 'afoo'),
(r'^$', 'foo'),
Expand Down
5 changes: 3 additions & 2 deletions vladiate/validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,13 +119,14 @@ def bad(self):
class RegexValidator(Validator):
''' Validates that a field matches a given regex '''

def __init__(self, pattern=r'di^'):
def __init__(self, pattern=r'di^', empty_ok=False):
super(RegexValidator, self).__init__()
self.regex = re.compile(pattern)
self.empty_ok = empty_ok
self.failures = set([])

def validate(self, field, row={}):
if not self.regex.match(field):
if not self.regex.match(field) and (field or not self.empty_ok):
self.failures.add(field)
raise ValidationException(
"'{}' does not match pattern /{}/".format(field, self.regex))
Expand Down

0 comments on commit 776f054

Please sign in to comment.