Commits

Lynn Rees  committed 99d2620

[svn]

  • Participants
  • Parent commits d9015ca
  • Branches wsgiform
  • Tags svn.35, svn.36

Comments (0)

Files changed (1)

File branches/0.3/wsgiform/validators.py

 
 import re, urllib
 from xml.dom.expatbuilder import parseString
-from HTMLParser import HTMLParser
 
-
-# Miscellaneous specialized regexes
+# Specialized regexes
 _patterns = {
 # US Social Security Number - Dennis Flynn - regexlib.com 
 'ssn':r'(^|\s)(00[1-9]|0[1-9]0|0[1-9][1-9]|[1-6]\d{2}|7[0-6]\d|77[0-2])(-?|[\. ])([1-9]0|0[1-9]|[1-9][1-9])\3(\d{3}[1-9]|[1-9]\d{3}|\d[1-9]\d{2}|\d{2}[1-9]\d)($|\s|[;:,!\.\?])',
 'canada':r'^(N[BLSTU]|[AMN]B|[BQ]C|ON|PE|SK)$',
 # Credit Card - David Conorozzo - regexlib.com
 'creditcard':r'^3(?:[47]\d([ -]?)\d{4}(?:\1\d{4}){2}|0[0-5]\d{11}|[68]\d{12})$|^4(?:\d\d\d)?([ -]?)\d{4}(?:\2\d{4}){2}$|^6011([ -]?)\d{4}(?:\3\d{4}){2}$|^5[1-5]\d\d([ -]?)\d{4}(?:\4\d{4}){2}$|^2014\d{11}$|^2149\d{11}$|^2131\d{11}$|^1800\d{11}$|^3\d{15}$',
-# Malice protection - Shahar Bracha - regexlib.com
+# Malice detection - Shahar Bracha - regexlib.com
 'malice':r'(script)|(<)|(>)|(%3c)|(%3e)|(SELECT)|(UPDATE)|(INSERT)|(DELETE)|(GRANT)|(REVOKE)|(UNION)|(<)|(>)',
 # Malice protection - Brenden Salta - regexlib.com
 'notmalice':r'^[^<>`~!/@\#}$%:;)(_^{&*=|\'+]+$',
 'vat':r'((DK|FI|HU|LU|MT|SI)(-)?\d{8})|((BE|EE|DE|EL|LT|PT)(-)?\d{9})|((PL|SK)(-)?\d{10})|((IT|LV)(-)?\d{11})|((LT|SE)(-)?\d{12})|(AT(-)?U\d{8})|(CY(-)?\d{8}[A-Z])|(CZ(-)?\d{8,10})|(FR(-)?[\dA-HJ-NP-Z]{2}\d{9})|(IE(-)?\d[A-Z\d]\d{5}[A-Z])|(NL(-)?\d{9}B\d{2})|(ES(-)?[A-Z\d]\d{7}[A-Z\d])',
 }
 
-patterns = dict((k, re.compile(v)) for k, v in _patterns.iteritems()) 
+patterns = dict((k, re.compile(v)) for k, v in _patterns.iteritems())
 
-def chainvalidate(data, chain):
-    '''Validates against a chain of validating functions.'''
-    for v in chain:
-        # Load validator
-        if not isinstance(v, basestring):
-            validator = validators[v[0]]
-        else:
-            validator = validators[v]
-        try:
-            if len(v) == 3:
-                if not validator(data, v[1], v[2]): return False
-            elif len(v) == 2:
-                if not validator(data, v[1]): return False
-            else:
-                if not validator(data): return False
-        except:
-            return False
-    return True
+def getvalidator(chain):
+    '''Returns a chained validator.
+
+    @param chain List of validator names.
+    '''
+    return ChainValidator(chain)
 
 def _validate(key, data):
     '''Validates data by key.'''
     '''Validates that data is a US phone number.'''
     return _validate('usphone', data)
 
-validators = dict(
-members=ismember,
-range=inrange,
-ascii=isascii,
-unicode=isunicode,
-number=isnumber,
-float=isfloat,
-alpha=isalpha,
-alphanum=isalphanum,
-space=isspace,
-cap=istitle,
-upper=isupper,
-lc=islower,
-length=islength,
-empty=isempty,
-# User submissions
-malice=malicious,
-notmalice=notmalicious,
-xml=isxml,
-# Network Addresses
-ip4=isip4,
-ip6=isip6,
-macaddr=ismacaddr,
-email=isemail,
-url=isurl,
-liveurl=isliveurl,
-# Password
-password=ispassword,
-# Postal codes
-zip=iszip,
-ukpost=isukpost,
-napost=isnapost,
-# Territory names
-province=isprovince,
-state=isstate,
-# Dates
-datetime=isdatetime,
-edatetime=isedatetime,
-# Numbers
-creditcard=iscreditcard, 
-isbn=isisbn,
-ssn=isssn,
-vat=isvat,
-usd=isusd, 
-# Phone numbers
-phone=isphone,
-ukphone=isukphone,
-intlphone=isintlphone,
-usphone=isusphone)
+# Registry of validators
+validators = dict(members=ismember, range=inrange, ascii=isascii,
+    unicode=isunicode, number=isnumber, float=isfloat, alpha=isalpha,
+    alphanum=isalphanum, space=isspace, cap=istitle, upper=isupper,
+    lc=islower, length=islength, empty=isempty, malice=malicious,
+    notmalice=notmalicious, xml=isxml, ip4=isip4, ip6=isip6,
+    macaddr=ismacaddr, email=isemail, url=isurl, liveurl=isliveurl,
+    password=ispassword, zip=iszip, ukpost=isukpost, napost=isnapost,
+    province=isprovince, state=isstate, datetime=isdatetime, 
+    edatetime=isedatetime, creditcard=iscreditcard, isbn=isisbn,
+    ssn=isssn, vat=isvat, usd=isusd, phone=isphone, ukphone=isukphone,
+    intlphone=isintlphone, usphone=isusphone)
+
+
+class ChainValidator(object):
+
+    '''Class to build a chain of validators'''    
+
+    def __init__(self, chain):
+        self.chain = chain
+
+    def __call__(self, data):
+        '''Validates against a chain of validating functions.'''
+        for v in self.chain:
+            # Load validator
+            if not isinstance(v, basestring):
+                validator = validators[v[0]]
+            else:
+                validator = validators[v]
+            # One validation failure invalidates the entire chain
+            try:
+                if len(v) == 3:
+                    if not validator(data, v[1], v[2]): return False
+                elif len(v) == 2:
+                    if not validator(data, v[1]): return False
+                else:
+                    if not validator(data): return False
+            # Any exceptions cause validation failure
+            except:
+                return False
+        return True