Robbie Robbie - 1 year ago 123
Python Question

Chain FormEncode Validators


I have a form in TurboGears 2 that has a text field for a list of e-mails. Is there a simple way using ToscaWidgets or FormEncode to chain form validators for Set and Email or will I have to write my own validator for this?

Answer Source

I think it should be more like the below. It has the advantage of trying each email instead of just stopping at the first invalid. It will also add the errors to the state so you could tell which ones had failed.

from formencode import FancyValidator, Invalid
from formencode.validators import Email

class EmailList(FancyValidator):
    """ Takes a delimited (default is comma) string and returns a list of validated e-mails
        Set the delimiter by passing delimiter="A_DELIMITER" to the constructor.
        Also takes all arguments a FancyValidator does.  
        The e-mails will always be stripped of whitespace.
    def _to_python(self, value, state):
            values = str(value).split(self.delimiter)
        except AttributeError:
            values = str(value).split(',')
        validator = formencode.ForEach(validators.Email())
        validator.to_python(values, state)
        return [value.strip() for value in values]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download