<强>问题:

我在TurboGears中2的形式,具有一个文本字段的电子邮件的列表。是否有使用ToscaWidgets或FormEncode以连锁形式验证程序设置和电子邮件的简单方法或我将不得不写我自己的这个验证?

有帮助吗?

解决方案

我想应该是更像下方。它试图每封电子邮件,而不是仅仅在第一无效停止优势。这也将添加错误状态,所以你可以告诉哪些失败了。

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):
        try:
            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]

其他提示

http://formencode.org/Validator.html

另一个值得注意的验证器是formencode.compound.All - 这是一个化合物验证器 - 即,它是采用验证作为输入的验证器。模式是一个示例;在这种情况下,一切都需要验证的列表,并应用他们每个人轮流。 formencode.compound.Any是其称赞,使用第一确认器通过在其列表中。

我想要的是一个验证我可以坚持到现场像String和诠释验证器。我发现有没有办法做到这一点,除非我创造了我自己的验证。我在这里张贴的完整性的缘故,所以其他人可以受益。

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):
        try:
            values = str(value).split(self.delimiter)
        except AttributeError:
            values = str(value).split(',')
        returnValues = []
        emailValidator = Email()
        for value in values:
            returnValues.append( emailValidator._to_python(value.strip(), state) )
        return values

使用 FormEncode验证 - 管道和包装,则可以:

from formencode import validators, compound


compound.Pipe(validators.Wrapper(to_python=lambda v: v.split(',')),
              validators.Email())
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top