Dale
Dale

Reputation: 412

jsonschema Draft7 multiple custom types in python

I am trying to add several custom types to my validators

at the moment i have one that verifies date types. I want to add another to verify positive integers

from datetime import date

date_checker = Draft7Validator.TYPE_CHECKER.redefine("date", lambda _, instance: isinstance(instance, date))
custom_validator = validators.extend(Draft7Validator, type_checker=date_checker)
validator = custom_validator(schema={"type": "date"})
validator.validate(config, schema)

How can I add another different type to the same validator object?

Upvotes: 4

Views: 1328

Answers (1)

Dale
Dale

Reputation: 412

After playing with a few variations I got this working. I am not 100% sure if this is the best way to do it....but it works

date_checker = Draft7Validator.TYPE_CHECKER.redefine_many({
    "date": lambda _, instance: isinstance(instance, date),
    "pos_int": lambda _, instance: isinstance(instance, int) and instance >= 0
})

custom_validator = validators.extend(Draft7Validator, type_checker=date_checker)
validator = custom_validator(schema)
validator.validate(config)

Upvotes: 3

Related Questions