Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

conditional validation #75

Closed
marconi opened this issue Dec 6, 2012 · 2 comments
Closed

conditional validation #75

marconi opened this issue Dec 6, 2012 · 2 comments

Comments

@marconi
Copy link

marconi commented Dec 6, 2012

How can I achieve conditional validation?

Say I have two fields field_a and field_b, field_b is optional by default but it becomes required when field_a has certain values.

I've been looking at the existing validators and it seems it only receives the node that it should validate, how can I access other nodes within the same schema from a validator?

@mcdonc
Copy link
Member

mcdonc commented Dec 6, 2012

@mcdonc mcdonc closed this as completed Dec 6, 2012
@thruflo
Copy link

thruflo commented Mar 23, 2016

I'm over three years late to this thread but there is (now?!) another way to do this!

Use a deferred that conditionally returns colander.required:

@colander.deferred
def conditionally_required(node, kw):
    some_condition = # whatever conditional logic you want
    if some_condition:
        return colander.drop # won't be required (or return a default like `None`)
    return colander.required # will be required

This can then be used as the missing value when defining a schema node:

foo = colander.SchemaNode(
    colander.String(),
    missing=conditionally_required
)

As a concrete example, if you have the request bound to your schema as kw['request'] and you wanted to make foo required unless a field called action has the value cheat, you could use:

@colander.deferred
def required_unless_cheating(node, kw):
    request = kw['request']
    action = request.params.get('action')
    if action == 'cheat':
        return colander.drop
    return colander.required    

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants