Re: Need help validating a form with dynamic fields

Ian Bicking <[email protected]> Fri, 08 Aug 2008 13:24:16 -0500
Newsgroups gmane.comp.python.formencode
Message-ID <[email protected]>
Matthew Wilson wrote:
> I'm dynamically generating form elements.  for example, each user has
> many magazine subscriptions.  So I make a checkbox for each
> subscription named something like "name_${subscriptionID}".  How can I
> write a validator when the name isn't known?
> 
> I want to validate that every field that starts with the string
> "name_" has a valid integer.
> 
> How can I do this?

Ideally, you'd use field names like name-1.checkbox and 
name-1.subscriptionID.  Then after using variabledecode you'll get 
something like:

{'name': [{'checkbox': 'on', 'subscriptionID': '1234'}]}

You can then use a validator like:

class CheckValidator(Schema):
     subscriptionID = Int(not_empty=True)
     checkbox = StringBoolean(if_missing=False)

class MySchema(Schema):
     name = ForEach(CheckValidator())


If you can't change your field names, you'll have to create a 
FormValidator (subclass that class) and check the dictionary of all 
inputs, and apply that check in your main schema with chained_validators 
or pre_validators.

-- 
Ian Bicking : [email protected] : http://blog.ianbicking.org

-------------------------------------------------------------------------
This SF.Net email is sponsored by the Moblin Your Move Developer's challenge
Build the coolest Linux based applications with Moblin SDK & win great prizes
Grand prize is a trip for two to an Open Source event anywhere in the world
http://moblin-contest.org/redirect.php?banner_id=100&url=/