jazzband / jazzband/jsonmodels

ListField: Add validation support for the elements values in the list

Open
#110 1 comment 0 reactions 1 assignee Claimed by @beregond View on GitHub
Dominant language
Python
Stars
343
Forks
50
PR merge metrics
No merged PRs in 30d

Description

Right now the `ListField` class supports type validation on its elements, and validation agains the list itself (length etc.)
But there is no easy way to specify validators that should be applied to **every** item in the list.

For example, I might want a `ListField` of `int`s, where all the items must be in the range `[0, 10]`.

One might create the following validator:
```py
class ElementsValidator(object):
def __init__(self, *item_validators):
self.item_validators = item_validators

def validate(self, value):
for item in value:
for v in self.item_validators:
v.validate(item)

class Foo(models.Base):
my_list = fields.ListField(int, validators=(
ElementsValidator(validators.Min(0), validators.Max(10))
))
```

While this example will work, It has some problems:
1. It will be very hard to modify the schema from this validator, as it needs to touch some schema elements created by the `ListField` itself, which might cause conflicts.
2. It will be very hard to support different validation for each supported type in the list.

Since the **type** of each element of the list, and its **validators** actually creates one schema, I think that this feature should be implemented by the library itself, and not by custom validator.

I have no idea how to implement this cleanly without breaking the current API of `ListField` though...

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.