Re: only validate some field if another is set to something
Ian Bicking <[email protected]>
| Newsgroups | gmane.comp.python.formencode |
|---|---|
| Message-ID | <[email protected]> |
Elvelind Grandin wrote:
> Hi.
>
> I want to only validate certain fields if another is a certain value.
>
> http://paste.turbogears.org/paste/1178
>
> I use this code and it works fine.
>
> the problem is that the _to_python method for the NiceHTML validator
> is called, but the returned argument is ignored.
You aren't returning values that make sense.
formencode.validators.RequireIfMissing is more the pattern of what you
want. Or FieldsMatch, or one of those.
You could probably generalize what you are thinking about like:
class ValidateWhenTrue(Schema):
# Set this to some function:
condition = None
def to_python(self, value_dict, state):
if not self.condition(value_dict, state):
# don't do anything
return value_dict
return Schema.to_python(self, value_dict, state)
class ValidateOptional(ValidateWhenTrue):
def condition(self, value_dict, state):
return not value_dict.get('some_field')
some_other_field = SomeValidator()
--
Ian Bicking | [email protected] | http://blog.ianbicking.org
| Write code, do good | http://topp.openplans.org/careers
-------------------------------------------------------------------------
Take Surveys. Earn Cash. Influence the Future of IT
Join SourceForge.net's Techsay panel and you'll get the chance to share your
opinions on IT & business topics through brief surveys-and earn cash
http://www.techsay.com/default.php?page=join.php&p=sourceforge&CID=DEVDEV