mikeywaites / kim

Kim: A JSON Serialization and Marshaling framework
http://kim.readthedocs.org/en/latest/
Other
317 stars 17 forks source link

Support multiple/reusable top level validate methods #28

Closed jackqu7 closed 9 years ago

jackqu7 commented 10 years ago

perhaps with hooks/decorator interface?

krak3n commented 10 years ago

Here is a complex validation example:

Password:

Email:

If fields at validation were aware of the marshal data then this is fairly trivial to implement and can easily be reused with a single callable.

class RequiredIf(object):

    def __init__(self, field):
        self.field = field

    def __call__(self, value, data):
        if self.field in data:
            if value is None:
                raise ValidationError('This is required')

class FooSerializer(SQASerializer):
    __model__ = Foo

    foo = Field(t.String, required=False)
    bar = Field(t.String, required=False, extra_validators=[
        RequiredIf('foo')
    ])

Obviously this is quite a philosophical change for Kim, no field should ever be "aware" of another. Personally, I don't see a problem with a fields validators being "aware" of the data provided when marshalling for validation concerns.

I don't feel a top level validator in the serializer is the best place for this, mainly due to bug #29 but also it makes reuse quite tricky, yes you could have a common callable multiple serializers could use through inheritance, mixins etc, but personally I do not feel this is particularly elegant in this situation. A top level validation method should be a last resort for some really bespoke validation requirements imo.

Thanks,

Chris