2

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?

steve
  • 423
  • 6
  • 16
  • Can we get a code sample, so we have more context? – MikeVaughan May 03 '11 at 22:38
  • I am only using the default validators, in my case "NotEmpty". So in my example, I have two form fields, State and Country, and I only want State to be NotEmpty when Country is US. Otherwise, State could be empty. – steve May 04 '11 at 19:28

1 Answers1

0

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.

Gevatter Gaul
  • 141
  • 1
  • 5
  • there's gotta be better validation libraries out there. im using this cause of work but having an option like `not_empty` is already the start of a red flag in my book. – dtc Oct 05 '17 at 18:27