Back to index

plone3  3.1.7
RegexValidator.py
Go to the documentation of this file.
00001 try:
00002     from Products.validation.interfaces.IValidator import IValidator
00003 except ImportError:
00004     import sys, os
00005     sys.path.insert(0, os.path.join(os.path.dirname(__file__), os.pardir))
00006     from interfaces.IValidator import IValidator
00007     del sys, os
00008 
00009 import re
00010 from types import StringType
00011 
00012 def ignoreRE(value, expression):
00013     ignore = re.compile(expression)
00014     return ignore.sub('', value)
00015 
00016 class RegexValidator:
00017     __implements__ = IValidator
00018 
00019     def __init__(self, name, *args, **kw):
00020         self.name = name
00021         self.title = kw.get('title', name)
00022         self.description = kw.get('description', '')
00023         self.errmsg = kw.get('errmsg', 'fails tests of %s' % name)
00024         self.regex_strings = args
00025         self.ignore = kw.get('ignore', None)
00026         self.regex = []
00027         self.compileRegex()
00028 
00029     def compileRegex(self):
00030         for r in self.regex_strings:
00031             self.regex.append(re.compile(r))        
00032     
00033     def __getstate__(self):
00034         """Because copy.deepcopy and pickle.dump cannot pickle a regex pattern
00035         I'm using the getstate/setstate hooks to set self.regex to []
00036         """
00037         d = self.__dict__.copy()
00038         d['regex'] = []
00039         return d
00040     
00041     def __setstate__(self, dict):
00042         self.__dict__.update(dict)
00043         self.compileRegex()
00044 
00045     def __call__(self, value, *args, **kwargs):
00046         if type(value) != StringType:
00047             return ("Validation failed(%(name)s): %(value)s of type %(type)s, expected 'string'" %
00048                     { 'name' : self.name, 'value': value, 'type' : type(value)})
00049 
00050         ignore = kwargs.get('ignore', None)
00051         if ignore:
00052             value = ignoreRE(value, ignore)
00053         elif self.ignore:
00054             value = ignoreRE(value, self.ignore)
00055 
00056 
00057         for r in self.regex:
00058             m = r.match(value)
00059             if not m:
00060                 return ("Validation failed(%(name)s): '%(value)s' %(errmsg)s" % 
00061                         { 'name' : self.name, 'value': value, 'errmsg' : self.errmsg})
00062         return 1