Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between Cerberus Custom Rules and Custom Validators?

From the documentation, it is not clear to me what the difference in use case for the Custom Rule and the Custom Validators are. In the examples given in the documentation, the only difference is an extra if statement that checks the value of is_odd in the custom rule. When should I prefer the Custom Rule, and when should I prefer the Custom Validator?


Custom Rule

schema = {'amount': {'isodd': True, 'type': 'integer'}}
from cerberus import Validator

class MyValidator(Validator):
    def _validate_isodd(self, isodd, field, value):
        """ Test the oddity of a value.

        The rule's arguments are validated against this schema:
        {'type': 'boolean'}
        """
        if isodd and not bool(value & 1):
            self._error(field, "Must be an odd number")

Custom Validator

from cerberus import Validator
schema = {'amount': {'validator': 'oddity'}}

class AValidator(Validator):
    def _validator_oddity(self, field, value):
       if value & 1:
           self._error(field, "Must be an odd number")
like image 950
darthbith Avatar asked Sep 11 '16 17:09

darthbith


1 Answers

You use the validator rule when you want to delegate validation of a certain field's value to a custom function or method (the latter is references as string in a schema), like so:

>>> def oddity(field, value, error):
...   if not value & 1:
...     error(field, "Must be an odd number")

>>> schema = {'amount': {'validator': oddity}}
>>> v = Validator(schema)
>>> v.validate({'amount': 10})
False

>>> v.errors
{'amount': 'Must be an odd number'}

>>> v.validate({'amount': 9})
True

Note that the signature of these is fixed, they take exactly field (the field's name in the document), value and error (a method to submit errors) as arguments.

Custom rules can only be defined in a Validator subclass. In contrast to the validator rule where the validating callable is defined as constraint, for custom rules constraints can be defined in a schema that are also passed to the custom rule implementation (in this answer's example it's named other). Therefore, the behaviour of a rule can be controlled in a schema.

It appears that the documentation for the validator rule is misleading if not plain wrong, and I should go and fix it as soon as possible! Thanks for reporting.

like image 175
Nicola Iarocci Avatar answered Sep 26 '22 01:09

Nicola Iarocci