Table of Contents

Related List Component Custom Validator

Inherit from the class RelatedListComponentCustomValidator and override the desired validation methods in order to implement a concrete validator for a Related List Component.

Validation methods

  • ValidateComponentOnSaveAsync: Use this method to perform a validation that requires looking simultaneously at all new, modified or removed rows from a Related List Component.

  • ValidateEntityOnSaveAsync

    • Use this method to perform validations on the fields of each new and modified rows of a Related List Component.

Dependency Injection

MIB supports dependency injection in concrete validators. Click here for more information.

Example

In this hypothetical validation, we override the validation methods ValidateComponentOnSaveAsync and ValidateEntityOnSaveAsync.

We use the inherited method AddNotification to add notifications that describe issues with the persistence data.

Key points

  • Notifications will be aggregated and displayed to the user.
  • Dictionary keys can be used in the messages.
public class MyConcreteRelatedListComponentValidator : RelatedListComponentCustomValidator
{
    // Data scoped validation    
    public override Task ValidateEntityOnSaveAsync(ReadOnlyEntityData entity, RelatedListComponentContext context, CancellationToken cancellationToken)
    {
        // We check if the field `SALES_EMAIL` has a valid e-mail address.
        if(entity.ModifiedFields.TryGetValueAsString("SALES_EMAIL", out var email))
        {
            if (!EmailValidator.IsValid(email))
            {
                AddNotification(new Notification("Please provide a valid email"));
            }
        }

        return Task.CompletedTask;
    }

    // Component scoped validation        
    public override async Task ValidateComponentOnSaveAsync(RelatedListComponentPersistenceData data, RelatedListComponentContext context, CancellationToken cancellationToken)
    {
        // Checking that after all the changes, there is at least one related entity.
        int previouslyRelatedItemsCount = await MyHelper.GetRelatedItemsCountAsync(entityId: .MainMibObjectIDs.First(), 
            mainMediaType: context.MainMediaType.Name,
            relatedMediaType: context.ComponentMediaType.Name,
            apiClient: client,
            cancellationToken);
        
        int currentRelatedItemsCount = previouslyRelatedItemsCount 
            - data.RemovedRelations.Count 
            + data.NewEntities.Count 
            + data.AddedEntities.Count;

        if (currentRelatedItemsCount < 1)
        {
            AddNotification(new Notification($"At least one item should be related in component"));
        }
    }
}