question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Pass schema's context to validation functions

See original GitHub issue

I am thinking about a way to pass context to validation function.

Currently validation function expect exactly one argument, value of a field. Maybe Field._validate method can check with inspect.getargspec and if function expect two arguments, send schema’s context as second argument?

I know that context is available in validation methods declared with @validates decorator, but I want to reuse validation function in different schemas with different fields.

Issue Analytics

  • State:open
  • Created 8 years ago
  • Reactions:4
  • Comments:16 (10 by maintainers)

github_iconTop GitHub Comments

6reactions
deckar01commented, Jul 14, 2016

@kevgliss You can use the existing @validate_schema decorator to validate against the schema context. The field_names parameter of the ValidationError exception allows you to specify which field(s) the error belongs to.

class IPSchema(Schema):
    cidr = fields.String()

   @validate_schema
   def valid_network(self, data):
        cidr = data['cidr']
        if cidr not in self.context.get('whitelisted_networks', []):
            raise ValidationError('Network {0} is not allowed'.format(cidr), ['cidr'])
3reactions
deckar01commented, Jul 14, 2016

I want to reuse validation function in different schemas with different fields.

I didn’t fully digest this requirement the first time around.

Currently you would have to:

def validate_foo(foo, field_name, context):
    if foo not in context['bar']:
        raise ValidationError('Foo must be in bar', [field_name])

class ItemSchema(Schema):
    quantity = fields.Integer()

    @validates_schema
    def validate_quantity(self, data):
        validate_foo(data['quantity'], 'quantity', self.context)

class AnotherSchema(Schema):
    quantity = fields.Integer()

    @validates_schema
    def validate_quantity(self, data):
        validate_foo(data['quantity'], 'quantity', self.context)

but it would be a lot more convenient if you had access to the context in a field validator:

@pass_schema_context
def validate_foo(foo, context):
    if foo not in context['bar']:
        raise ValidationError('Foo must be in bar')

class ItemSchema(Schema):
    quantity = fields.Integer(validate=validate_foo)

class AnotherSchema(Schema):
    quantity = fields.Integer(validate=validate_foo)

So Field._validate() would need to be able to efficiently identify when a validator has been wrapped in @pass_schema_context decorator and provide the schema context as an additional argument.

I’m not sure it makes sense to use a decorator outside of the schema body in order to identify that a field-level validator expects schema-level data. All the other decorators are used to register a processor with a specific schema class.

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to use Yup context variables in Formik validation
This article demonstrates the power of custom functions with Yup context variables and Formik validation in React forms.
Read more >
Ajv options - Ajv JSON schema validator
Pass validation context to compile and validate keyword functions. If this option is true and you pass some context to the compiled validation...
Read more >
Extending Schemas — marshmallow 3.19.0 documentation
You can register schema-level validation functions for a Schema using the marshmallow.validates_schema decorator. By default, schema-level validation errors ...
Read more >
Validation Schema | Fonk Doc
What happens if we need to add addional context information to the validator function, for instance passing a custom error message ?
Read more >
Validation - VeeValidate
Create a form context with the validation schema useForm({ ... You can pass your schemas to the useForm function using the same validationSchema...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found