8

如何在 Deform/Colander 中定义一个自定义验证器,该验证器可以访问所有节点值。我需要访问两个字段中的值以确定特定值是否有效?

4

2 回答 2

3

要为所有滤锅字段放置验证器,我们可以简单地这样做

验证器方法:

def user_DoesExist(node,appstruct):
if DBSession.query(User).filter_by(username=appstruct['username']).count() > 0:
    raise colander.Invalid(node, 'Username already exist.!!')

架构:

class UserSchema(CSRFSchema):
username = colander.SchemaNode(colander.String(), description="Extension of the user")
name = colander.SchemaNode(colander.String(), description='Full name')
extension = colander.SchemaNode(colander.String(),description='Extension')
pin = colander.SchemaNode(colander.String(), description='PIN')

看法:

@view_config(route_name='add_user', permission='admin', renderer='add_user.mako')
def add_user(self):
    #Here you can provide validator method as a parameter. And you can validate any field you want.
    schema = UserSchema(validator = user_DoesExist).bind(request=self.request)
    form = deform.Form(schema, action=self.request.route_url('add_user'), buttons=('Add User','Cancel'))

如果我在我的场景中错了,请纠正我。

谢谢

于 2013-08-27T06:44:22.593 回答
2

Tangibly the answer is:

def verify_email_validator(form, values):
    if values['email_address'] != values['verify_email']:
        raise Invalid(form, 'Email values do not match')

class MySchema(MappingSchema):

    def __init__(self, *args, **kwargs):
        super(KickEntrySchema, self).__init__(*args, **kwargs)
        self.validator=verify_email_validator  # entire form validator

    email_address = SchemaNode(Email())
    verify_email = SchemaNode(Email())

Note the form validator is invoked only if none of the individual field validators raise an error.

于 2013-08-23T08:00:02.693 回答