如何让Pylons formencode验证器忽略某些字段

时间:2011-04-28 19:10:44

标签: validation pylons formencode

我有一个表单,其中包含一些输入文本框以及一些选择框。我有验证在文本框上完美运行。我不在乎是否有任何选择框被保留,但每次我提交表格时它会进入一个pylons错误页面,上面写着“无效:请为...输入值”但我不希望这样发生。

这是我的验证器功能:

class Registration(formencode.Schema):
    allow_extra_fields=True
    first_name = formencode.validators.String(strip=True, not_empty=True)
    last_name = formencode.validators.String(strip=True, not_empty=True)
    address = formencode.validators.String(strip=True, not_empty=True)
    phone = formencode.validators.PhoneNumber(strip=True, not_empty=True)
    email = formencode.validators.Email(resolve_domain=True, not_empty=True)
    messages = {
        'tooLow': "You must be at least 18 in order to register for an event.",
        'tooHigh': "You obviously are not that old.  Please enter your actual age.",
    }
    age = formencode.validators.Int(min=18, max=999, not_empty=True, messages=messages)

我认为如果使用allow_extra_fields = True,它将允许函数中未提供的表单中的字段如果保留为空/默认值则通过。我有一些名为hear,frequency和level的框,应该被忽略。

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:2)

formencode.validators方法上:

  • 如果表单提交字段且值为空字符串,请使用not_empty=False。 param not_empty false就是这样说的:empty是一个有效值。
  • 如果字段不存在,请使用if_missing = None,将结果设置为None

答案 1 :(得分:0)

我认为你应该添加以下一行

filter_extra_fields = True