Luper Rouch
Luper Rouch

Reputation: 9502

How do I validate list:string fields with web2py?

Searching through gluon.validators I came across IS_LIST_OF() so I tried to add it to my model:

db.define_table("emails_list",
    Field("recipients", "list:string", requires=IS_LIST_OF(IS_EMAIL(
        error_message="Invalid email")))
)

I verified that recipients are correctly added to the database (I use SQLFORM by the way), but validation just doesn't happen.

Upvotes: 1

Views: 1056

Answers (1)

mr.freeze
mr.freeze

Reputation: 14054

From what I can tell through debugging, validators are stripped from list:* fields for some reason. This must be a bug. You can work around it by using the onvalidation attribute of form.accepts. Here's an example:

In your model :

def validate_email(form):
    for eml in form.vars.recipients:
        out,ers = IS_EMAIL()(eml)
        if ers:
            form.errors.receipients = ers

db.define_table("emaillist",
    Field("recipients", "list:string"))

In your controller:

def listtest():
    form = SQLFORM(db.emaillist)
    if form.accepts(request.vars,session,
                    onvalidation=validate_email):
        response.flash = "Got it"
    else:
        response.flash = form.errors
    return dict(form=form)

Upvotes: 3

Related Questions