Validator helpers

Validators are the same as any other subclass of Spec in that it has a normalise method that takes in meta and val and returns a new val.

It is convention that a validator subclasses Validator and implements a validate method. This means NotSpecified values are ignored and any specified value goes through the validate method.

It is the job of the validator to raise a subclass of BadSpec if something is wrong, otherwise just return val.

The following is all available under delfick_project.norms.va. For example:

from delfick_project.norms import va, BadSpecValue

class divisible_by_two(va.Validator):
    def validate(self, meta, val):
        val = sb.integer_spec().normalise(meta, val)
        if val % 2 != 0:
            raise BadSpecValue("Value was not divisible by two", got=val, meta=meta)
        return val
class delfick_project.norms.validators.Validator(*pargs, **kwargs)

A specification that either returns NotSpecified if val is NotSpecified or simply calls self.validate.

validate(meta, val)

Subclasses of Validator must implement this method.

It will do validation on a value.

If the value is invalid then raise an instance of BadSpec.

Otherwise return the value

has_either

Usage
has_either([key1, ..., keyn]).normalise(meta, val)

Will complain if the val.get(key, sb.NotSpecified) returns sb.NotSpecified for all the choices.

I.e. A valid dictionary has either one of the specified keys!

has_only_one_of

Usage
has_only_one_of([key1, ..., keyn]).normalise(meta, val)

Will complain if the val.get(key, sb.NotSpecified) returns sb.NotSpecified for all but one of the choices.

I.e. A valid dictionary must have exactly one of the specified keys!

either_keys

Usage
either_keys([k1, k2], [k3]).normalise(meta, val)

Will complain if the value is not a dictionary

Will complain if the keys from one group are mixed with keys from another group

Will complain if keys from one group appear without the rest of the keys in that group

Will not complain if unspecified keys are in the val

no_whitespace

Usage
no_whitespace().normalise(meta, val)

Raises an error if we can find the regex \s+ in the val.

no_dots

Usage
no_dots().normalise(meta, val)

# or

no_dots(reason="dots are evil!").normalise(meta, val)

This will complain if val contains any dots

It will use the reason to explain why it’s an error if it’s provided.

regexed

Usage
regexed(regex1, ..., regexn).normalise(meta, val)

This will match the val against all the regex and will complain if any of them fail, otherwise the val is returned.

deprecated_key

Usage
deprecated_key(key, reason).normalise(meta, val)

This will raise an error if val is nonempty and contains key. The error will use reason in it’s message.

choice

Usage
choice(choice1, ..., choicen).normalise(meta, val)