Skip to content

Commit

Permalink
Add RequireValue validation helper
Browse files Browse the repository at this point in the history
  • Loading branch information
amol- committed Mar 18, 2024
1 parent 96d74b0 commit cea3e93
Showing 1 changed file with 36 additions and 1 deletion.
37 changes: 36 additions & 1 deletion tg/validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,9 +158,44 @@ def __init__(self, func, msg=lazy_ugettext('Invalid'), default=None):
self._default = default

def to_python(self, value, state=None):
value = value or self._default
if RequireValue.is_empty(value):
if self._default is None:
raise TGValidationError(self._msg, value)
return self._default

try:
return self._func(value)
except:
raise TGValidationError(self._msg, value)


class RequireValue(object):
"""Mark a value as required during validation.
This is meant to be used when a value is required,
but not conversion needs to happen.
This is usually common for string values.
In case conversion has to happen, use :class:`Convert`
which will already fail if no value is provided.
Example::
@expose()
@validate({
'num': RequireValue('you must provide a number')
}, error_handler=insert_number)
def post_pow2(self, num):
return str(num*num)
"""
def __init__(self, msg=lazy_ugettext('Required')):
self._msg = msg

@staticmethod
def is_empty(value):
return value in (None, '', b'', [], {}, tuple())

def to_python(self, value, state=None):
if self.is_empty(value):
raise TGValidationError(self._msg, value)
return value

0 comments on commit cea3e93

Please sign in to comment.