What is the difference between Cerberus custom rules and custom validators?

From the documentation, I donโ€™t understand what the difference is in the use case for the user rule and user validators. In the examples given in the documentation, the only difference is the additional if , which checks the is_odd value in the user rule. When should I use a custom rule, and when should I use a 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 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") 
+5
source share
1 answer

You use the validator rule if you want to delegate the verification of a specific field value to a user-defined function or method (the latter is a link as a string in a schema), for example:

 >>> 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 them is fixed, they take exactly field (the name of the field in the document), value and error (the method of sending errors) as arguments.

Custom rules can only be defined in the validator subclass. Unlike the validator rule, where the verifying caller is defined as a restriction, for restrictions, user rules can be defined in the scheme, which are also passed to the implementation of the user rule (in this answer, it is called an example ). Therefore, the behavior of the rule can be controlled in the scheme.

The documentation for the validator rule validator to be misleading, if not completely wrong, and I have to go and fix it as soon as possible! Thank you for message.

+2
source

All Articles