Search code examples
pythonpyramiddeformcolander

How to do simple value check with error message in Deform/Colander


I'm implementing a simple 'tick to agree to terms and conditions box' in Deform/Colander.

So, I simply want to check that the box is checked and have an error message saying 'You must agree to T&C'.

I understand that I can use:

colander.OneOf([True]) 

to ensure the box is ticked. However, OneOf does not allow for a custom error message. What would the correct way to do this be?


Solution

  • Use a custom validator:

    def t_and_c_validator(node, value):
        if not value:
            raise Invalid(node, 'You must agree to the T&C')
    
    class MySchema(colander.Schema):
        t_and_c = colander.SchemaNode(
                      colander.Boolean(),
                      description='Terms and Conditions',
                      widget=deform.widget.CheckboxWidget(),
                      title='Terms and Conditions',
                      validator=t_and_c_validator,
                      )