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