开发者

formencode conditional validation

how do i validate a field conditionally based on the presence of another field. for example, only make "state" required only if "country" is "US".

thanks, steve

EDIT:

so i figured开发者_开发问答 to do this:

chained_validators = [validators.RequireIfPresent('state', present="country")]

but the error message is associated with "_the_form" instead of "state". is there a way to link it to the field instead?


Had the same problem during a project in my company. We wrote our own Formencode validator for this. We currently try to merge it with the main project. In the meantime you can download it here: https://github.com/GevatterGaul/formencode

There is also a Howto in, well, german: http://techblog.auf-nach-mallorca.info/2014/08/19/dynamische_formulare_validieren_mit_formencode/

But let me give you a quick rundown in the context of your example:

from formencode import validators
v = validators.RequireIfMatching('country', expected_value='US', required_fields=['state'])
v.to_python(dict(country='US', state='Virginia'))

The main benefit is, that in comparison to validators.RequireIfPresent, validators.RequireIfMatching only requires a field when a given field matches a given value. In your example, only if 'country' is 'US', then it requires the 'state' field.

Hope I could help.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜