Wagtail Validation for Blocks
See original GitHub issueThere is no documentation on how the validation for blocks works.
Pertinent section of the Wagtail docs
https://docs.wagtail.io/en/v2.13/advanced_topics/customisation/streamfield_blocks.html
Details
I just updated a project to Wagtail 2.13. Having some tests in place which check whether some custom validation logic within the clean
method of our blocks works we noticed these tests failing.
The tests check whether the error messages actually appear within the wagtail editing interface.
Please consider following example:
def clean(self, value):
if bool(value.get("link_text")) != bool(value.get("url")):
raise ValidationError(
"ValidationError in DllElementBlock",
params={
"link_text": ErrorList(["Please fill both fields."])
},
)
return super().clean(value)
I have a StructBlock
with a field url
and a field link_text
. Both fields need to be either empty or filled.
After the upgrade the error message did not appear.
I changed the validation to the following:
def clean(self, value):
if bool(value.get("link_text")) != bool(value.get("url")):
raise StructBlockValidationError( # <--- changed exception
{"link_text": ErrorList(["Please fill both fields."])},
)
return super().clean(value)
Using StructBlockValidationError
fixed the issue! The error message is shown.
I would suggest to add some documentation on how to validate blocks and which exceptions to use.
Issue Analytics
- State:
- Created 2 years ago
- Reactions:7
- Comments:9 (3 by maintainers)
Top GitHub Comments
The current implementation of validation for StructBlock / ListBlock / StreamBlock was not really intended to be used for custom validation in end-user code - it was only designed to deal with propagating errors that occur in FieldBlocks, and there are some design decisions that made sense in that context but are more dubious when the error originates from the StructBlock / ListBlock / StreamBlock itself - e.g. the data of a ListBlock validation error being a list of either
None
or aValidationError
instance for each of its child blocks. If we’re going to make this a developer-facing API (and I think we should…) then we really need to redesign it to be more user-friendly, rather than document what’s already there.Just for context, @KalobTaulien includes a lesson on StreamField validation affected by this 😌