Permalink
Browse files

Added a new validator `UUIDValidator` (+test) for UUID/GUIDs

	modified:   ../../tests/test_validation.py
	modified:   __init__.py
	modified:   validation.py
  • Loading branch information...
RobertSudwarts committed Jul 3, 2013
1 parent 75001ec commit ebea7f30b892eb426ca788b26112b5db6d845260
Showing with 37 additions and 1 deletion.
  1. +6 −0 tests/test_validation.py
  2. +1 −1 tw2/core/__init__.py
  3. +30 −0 tw2/core/validation.py
@@ -408,6 +408,12 @@ class TestIPAddressValidator(tb.ValidatorTest):
attrs = [{}, {}]
params = ['123.123.123.123', 'asdf']
expected = [None, ValidationError]
class TestUUIDValidator(tb.ValidatorTest):
validator = UUIDValidator
attrs = [{}, {}]
params = ['34a9c4dd-1562-4413-bb27-a439292a5e61', 'asdf']
expected = [None, ValidationError]
class TestValidatorMisc(TestCase):
@@ -27,7 +27,7 @@
RegexValidator, IntValidator, OneOfValidator, DateValidator,
DateTimeValidator, ValidationError, Invalid, EmailValidator,
UrlValidator, IpAddressValidator, StringLengthValidator,
ListLengthValidator, RangeValidator, MatchValidator,
ListLengthValidator, RangeValidator, MatchValidator, UUIDValidator,
BoolValidator, BlankValidator, safe_validate, EmptyField,
CompoundValidator,
Any, All,
@@ -7,6 +7,7 @@
import copy
import functools
import webob
import uuid
from i18n import _
@@ -507,6 +508,35 @@ def validate_python(self, value, state=None):
raise ValidationError('badnetblock', self)
class UUIDValidator(Validator):
"""
Confirm the value is a valid uuid and convert to uuid.UUID.
"""
msgs = {
'badregex': ('baduuid', _('Value not recognised as a UUID')),
}
regex = re.compile(\
'[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}')
def _validate_python(self, value, state=None):
if not self.regex.search(str(value)):
raise ValidationError('badregex', self)
def _convert_to_python(self, value, state=None):
try:
return uuid.UUID( "{%s}" % value )
except ValueError:
raise ValidationError('baduuid', self)
def _convert_from_python(self, value, state=None):
return str(value)
class MatchValidator(Validator):
"""Confirm a field matches another field

0 comments on commit ebea7f3

Please sign in to comment.