Small tutorial how to access content type class instance/object that is being validated from within Archetype’s validator
Recently I needed a validator that will not check against some constant value or expression. I wanted a check against other attributes of the same object that was being validated. I’ve never done such thing so I’ve searched the web for a hint or recipe. But I couldn’t find an example that solve this particular case. I’ve found some nice tutorials about Archetype’s validators (see below). But all examples were simple checks against string value or regular expression. There was no hint how to access validate object itself.
Finally I’ve research “the source” and run few tests. I’ve found 3 possible solutions to my problem:
- Overriding mutator. Add mutator parameter to field in schema and implement this method inside class. Then I’d be able to check condition against other fields of the class and probably raise an error if the condition failed. But the exception will show error page instead nice standard validator information on edit page.
- Pre validation. Sydnei da Silva describes in his tutorial method pre_validate that is called at the beginning of validation. But I’d have to parse REQUEST manually and catch all other exceptions. This didn’t sound interesting to me.
- **kwargs parameter in validator __call__ method. This is really what I wanted. And I found this after writing values of that variable on the console.
Available validator parameters
Parameter kwargs stores really useful information. It is a Python dictionary with following keys:
- field – validated field object,
- errors – errors list,
- REQUEST – current REQUEST object,
- instance – object instance, what I was looking for.
In __init__.py of the product we need to register validator.
from Products.validation import validation from validators import InstaceValidator validation.register(InstaceValidator( “checkListLength” ))
Our field in schema:
LinesField( “elements” , validators = ( “checkListLength” ,), widget=MultiSelectionWidget( format = “checkbox” , label = “Elements” , description = “Select elements.” ,), ),