Custom StreamField blocks and field validation

549 views
Skip to first unread message

Jean-Nicolas Kuttler

unread,
Jun 20, 2016, 10:32:00 AM6/20/16
to Wagtail support
I use custom StreamField blocks based on StructBlock but can't seem to figure out how to validation my input fields. Has anybody done this or can point me in the right direction? From looking at the wagtail source no clean_foo methods are called and clean() apparently expects some special return value, not like a normal Django form.

Matthew Westcott

unread,
Jun 22, 2016, 7:46:02 AM6/22/16
to wag...@googlegroups.com
Hi Jean-Nicolas,

There's currently no way to implement custom validation at the StructBlock level - the current code assumes that any ValidationErrors thrown while validating the StructBlock always originate from one of the child blocks. However, you can add custom validation on an input field within the StructBlock by subclassing the block class:

class NoSpacesCharBlock(blocks.CharBlock):
def clean(self, value):
clean_value = super(NoSpacesCharBlock, self).clean(value)
if ' ' in clean_value:
raise ValidationError("This field may not contain spaces.")
return clean_value

Cheers,
- Matt
Reply all
Reply to author
Forward
0 new messages