iro/validate.py
branchdevel
changeset 114 1ed072cc6793
parent 110 601fc908d9f1
child 115 323d06431100
--- a/iro/validate.py	Thu Jan 26 01:23:04 2012 +0100
+++ b/iro/validate.py	Fri Jan 27 15:01:59 2012 +0100
@@ -1,27 +1,57 @@
 import re
+from functools import wraps
+
 from inspect import getcallargs
 from .error import ValidateException
 
-def vuserhash(hash,field):
-    '''vailidate function for userhash'''
-    if not re.match(r'^[a-f0-9]{15,}$', hash.lower()):
+def boolean(value, field):
+    t=[True,"true",1]
+    f=[False,"false",0]
+    if value in t:
+        return True
+    elif value in f:
+        return False
+    else:
+        raise ValidateException(field=field, msg='%s is not boolean' % field)
+
+
+def validateHash(value,field,minlength=None,maxlength=None):
+    if not re.match(r'^[a-f0-9]*$', value.lower()):
         raise ValidateException(field=field)
-    return True
+    if minlength and len(value)<minlength:
+        raise ValidateException(field=field)
+    if maxlength and len(value)>maxlength:
+        raise ValidateException(field=field)
+    return value
 
-def validate(**kargs):
+def vuserhash(value,field):
+    '''vailidate function for userhash'''
+    return validateHash(value,field,minlength=15,maxlength=15)
+
+def validate(kwd,func, need=True,*args,**kargs):
     '''validate decorator
     use it like this:
-        @validate(userhash=vuserhash)
+        @validate(kwd=userhash, func=vuserhash)
         f(userhash)
-    that will validate usrhah with the function vuserhash.
+    that will validate usrhash with the function vuserhash.
     Every validate function should raise an Exception, if the the value is not valid'''
     def v(f):
+        @wraps(f)
         def new_f(*a,**k):
-            kp=getcallargs(f,*a,**k)
-            for i in kargs:
-                kargs[i](kp[i],i)
-            return f(*a,**k)
-        new_f.__name__ = f.__name__
+            kp=getcallargs(new_f.original,*a,**k)
+            try:
+                if need or kp[kwd] is not None:
+                    kp[kwd] = func(kp[kwd],kwd,*args,**kargs)
+                else:
+                    kp[kwd] = None
+            except KeyError:
+                if need:
+                    raise ValidateException(field=kwd,msg="%s is nessasary"%kwd)
+            return f(**kp)
+        try:
+            new_f.original=f.original
+        except AttributeError:
+            new_f.original=f
         return new_f
     return v