Reputation: 547
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?
Upvotes: 1
Views: 1590
Reputation: 25536
First, note that web2py validators are never at the level of the database, even when specified as part of the table definition -- they are always enforced at the level of the form.
The INPUT()
, SELECT()
, and TEXTAREA()
helpers that SQLFORM uses to build the form fields all take a "requires" attribute, which can be a single validator or list of validators. SQLFORM automatically copies the validators of the database table fields to the associated form widgets when the form is created. So, the easiest approach is to specify a validator for the database table field right before creating the SQLFORM:
def myform():
db.mytable.myfield.requires = IS_IN_SET(['a', 'b', 'c'])
form = SQLFORM(db.mytable).process()
return dict(form=form)
In that case, SQLFORM will copy the validator from db.mytable.myfield to the associated "myfield" widget in the form.
You can also add validators directly to the widgets after the form has been created (but before it is processed):
form = SQLFORM(db.mytable)
form.custom.widget.myfield['requires'] = IS_IN_SET(['a', 'b', 'c'])
form.process()
An alternative way to access the field widget:
form.element('input[name=myfield]')['requires'] = IS_IN_SET(['a', 'b', 'c'])
Upvotes: 2