Validation of block content

We want to add validation to fields on a block using a validation rule from ValidationRuleBase. Below is a simplified example where we are testing the field BlockWidth and want to make sure the field is not set to 0. The goal is to have this rule checking the block when it is saved and if something is not valid inform the user and prevent the save of the block.

public class TextBlockValidator : ValidationRuleBase<Block>
{
    private readonly Guid? _textBlockFieldTemplateSystemId;

    public TextBlockValidator(FieldTemplateService fieldTemplateService)
    {
        _textBlockFieldTemplateSystemId = fieldTemplateService.Get<BlockFieldTemplate>(BlockTemplateNameConstantsExtension.Textblock)?.SystemId;
    }

    public override ValidationResult Validate(Block entity, ValidationMode validationMode)
    {
        var result = new ValidationResult();

        if (_textBlockFieldTemplateSystemId == null)
            return result;

        if (entity.FieldTemplateSystemId != _textBlockFieldTemplateSystemId)
            return result;

        var blockWidth = entity.Fields.GetValue<int>(BlockFieldNameConstantsExtension.BlockWidth);
        if (blockWidth == 0)
        {
            result.AddError(BlockTemplateNameConstantsExtension.Textblock, "textfield.validation.missing.blockwidth".AsAngularResourceString());
            return result;
        }
        return result;
    }
}

However, this code is not run when we save the block, but at the time we publish the page the block is placed on. We get the error message on the top of the page, but even if it fails the page still gets published.

Is this the pattern for validating block content? Is there a way to get the validator to trigger when the block is saved and have it show the error message in the block editor instead?

Litium version: 8.11.0

When you save the block in the edit mode the information is stored on the DraftBlock entity, not the Block entity.

The page is published before each block, and it will be the individual block that get the validation message and should not be published. So the page is published but not the block.

Should we change the validator to inherit ValidationRuleBase<DraftBlock> and Validate(DraftBlock entity, ValidationMode validationMode) then?

I just tested and the answer is “yes”, it works as we wanted to.

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.