1

I know how to add validation to SQLFORM fields at the level of the database. However, I can't find anything about doing this at the level of individual forms. Ideally I would be able to have an existing SQLFORM and say something like:

form.field.requires = # some extra validator

Is there anything like this?

4

1 回答 1

2

首先,请注意 web2py 验证器从不在数据库级别,即使指定为表定义的一部分 - 它们始终在表单级别强制执行。

SQLFORM 用于构建表单字段的INPUT()SELECT()TEXTAREA()helper 都采用“requires”属性,该属性可以是单个验证器或验证器列表。SQLFORM 在创建表单时自动将数据库表字段的验证器复制到关联的表单小部件。因此,最简单的方法是在创建 SQLFORM 之前为数据库表字段指定一个验证器:

def myform():
    db.mytable.myfield.requires = IS_IN_SET(['a', 'b', 'c'])
    form = SQLFORM(db.mytable).process()
    return dict(form=form)

在这种情况下,SQLFORM 会将验证器从 db.mytable.myfield 复制到表单中关联的“myfield”小部件。

您还可以在创建表单之后(但在处理之前)直接将验证器添加到小部件:

form = SQLFORM(db.mytable)
form.custom.widget.myfield['requires'] = IS_IN_SET(['a', 'b', 'c'])
form.process()

访问字段小部件的另一种方法:

form.element('input[name=myfield]')['requires'] = IS_IN_SET(['a', 'b', 'c'])
于 2012-08-04T05:12:33.793 回答