Re: RequireIfPresent
Ian Bicking <[email protected]> Tue, 13 May 2008 17:49:44 -0500
| Newsgroups | gmane.comp.python.formencode |
|---|---|
| Message-ID | <[email protected]> |
[email protected] wrote: > Dear fellow Formencode Enthusiasts: > > I want to chain a field B to an existing field A, such that if user > inputs a value for field A, then field B is required, otherwise if field > A is empty, field B is not required. I looked at RequireIfPresent, and > I believe I know how to use it: > > >>> from formencode import validators > >>> ripi_01 = validators.RequireIfPresent('phone_type_pri', > present='primary_phone') > >>> ripi_01.to_python({'phone_type_pri':'', 'primary_phone':'510 420 > 4577'}) > > Invalid: You must give a value for phone_type_pri > >>> ripi_01.to_python({'phone_type_pri':'', 'primary_phone':''}) > {'phone_type_pri': '', 'primary_phone': ''} > >>> > > but I can't seem to get it to work in context of my schema. I get a > "Missing value" error message that at first made me conclude my schema > was expecting 'phone_type_pri' to be required, and yet when I do input a > value for phone_type_pri, e.g., 'home phone', I get the exact same error > message as before ! It seems no matter what I do (e.g., if I leave > primary_phone empty, if I select a value for phone_type_pri), I will get > the following error: > > phone_type_pri: Missing value > > I searched on Google for RequireIfPresent and "missing value" and saw at > least one other user (negus on the Pylons list) with this problem. > Please let me know if I am doing something wrong: > > class Appl_Form(formencode.Schema): > email = validators.Email(resolve_domain=True, not_empty=True) > confirm_email = validators.Email(not_empty=True) > primary_phone = validators.PhoneNumber() > phone_type_pri = validators.PlainText() > chained_validators = [validators.FieldsMatch('email', > 'confirm_email'), validators.RequireIfPresent('phone_type_pri', > present='primary_phone')] Schemas require the fields to be present unless you put if_missing=None in the validator. In this case you need: phone_type_pri = validators.PlainText(if_missing=None) I also added an explanation to the RequireIfPresent docstring. -- Ian Bicking : [email protected] : http://blog.ianbicking.org ------------------------------------------------------------------------- This SF.net email is sponsored by: Microsoft Defy all challenges. Microsoft(R) Visual Studio 2008. http://clk.atdmt.com/MRT/go/vse0120000070mrt/direct/01/