Is it possible to apply a validation rule from the rule set registry AND additional ad hoc rules?

17 Views Asked by At

In the example below, I create a custom rule 's3_rule' and add it to the rules_set_registry. 's3_rule' checks that the value is a string, and uses coerce to apply a function that adds 's3://' to the start of the value, if it is not there already. This works just fine.

from cerberus.validator import Validator, rules_set_registry


def s3_path(path: str):
    if path.startswith("s3://"):
        return path
    else:
        return "s3://" + path


rules_set_registry.extend(
    [
        (
            "s3_path",
            {
                "type": "string",
                "coerce": lambda v: v if v.startswith("s3://") is True else f"s3://{v}",
            },
        ),
        ("is_required", {"required": True}),
    ]
)

schema = {"path": "s3_path"}

v = Validator(schema)
print(v.validated({"path": "bucket/stage"}))
print(v.errors)

However, I would like to be able to apply my custom rule as well as other ad hoc rules as required. For example, in addition to 's3_path', I also want to set the field to be required.

I expected it would be possible to set a list of rules as below, but this does not work.

from cerberus.validator import Validator, rules_set_registry


def s3_path(path: str):
    if path.startswith("s3://"):
        return path
    else:
        return "s3://" + path


rules_set_registry.extend(
    [
        (
            "s3_path",
            {
                "type": "string",
                "coerce": lambda v: v if v.startswith("s3://") is True else f"s3://{v}",
            },
        ),
        ("is_required", {"required": True}),
    ]
)

schema = {"path": ["s3_path",{"required":True}]} # <-- How do I validate 'path' according to 's3_path' and some other ad hoc validation?

v = Validator(schema)
print(v.validated({"path": "bucket/stage"}))
print(v.errors)```

How do I validate 'path' according to 's3_path' and some other ad hoc validation?

0

There are 0 best solutions below