import re
from decorator import decorator
from twisted.internet import defer
from inspect import getcallargs
from .error import ValidateException
def vBool(value, field):
'''Validator for boolean values'''
t=[True, 1, "true", "True", "TRUE"]
f=[False, 0, "false", "False", "FALSE"]
if value in t:
return True
elif value in f:
return False
else:
raise ValidateException(field=field, msg='%s is not boolean' % field)
def vHash(value,field,minlength=None,maxlength=None):
'''Validator for hash values'''
if not re.match(r'^[a-f0-9]*$', value.lower()):
raise ValidateException(field=field)
if minlength and len(value)<minlength:
raise ValidateException(field=field)
if maxlength and len(value)>maxlength:
raise ValidateException(field=field)
return value
def vTel(value,field):
return value
def vEmail(value, field):
return value
def validate(kwd,func, need=True,*args,**kargs):
'''validate decorator
use it like this:
@validate(kwd=userhash, func=vuserhash)
f(userhash)
that will validate usrhash with the function vuserhash.
Every validate function should raise an Exception, if the the value is not valid'''
@decorator
def v(f,*a,**k):
kp=getcallargs(f,*a,**k)
def dfunc(*x,**y):
return None
try:
if need or kp[kwd] is not None:
dfunc=func
except KeyError:
if need:
raise ValidateException(field=kwd,msg="%s is nessasary"%kwd)
def _gotResult(value):
kp[kwd] = value
e = defer.maybeDeferred(f,**kp)
return e
d = defer.maybeDeferred(dfunc, kp[kwd],kwd,*args,**kargs)
return d.addCallback(_gotResult)
return v