Custom Validation

If you have a complex custom property, or want to do some custom checks on content or media before it's saved, this is where the IValidate comes in handy.

This is used internally to validate items before it's saved. To get one running you just need to implement the IValidate interface

public interface IValidate<T>
{
    Task<ValidateResult> Validate(T item);
}

Where T is the type of item you want to validate. Below shows our Content validate which firstly checks the Name is never null then checks for any properties that are required and makes sure a value is saved

public class ValidateContent(IMediator mediator) : IValidate<Models.Content>
{
    public async Task<ValidateResult> Validate(Models.Content item)
    {
        var validateResult = new ValidateResult();
        if (item.Name.IsNullOrWhiteSpace())
        {
            validateResult.ErrorMessages.Add("You cannot leave the name empty");
        }
        
        // This might be new content, so we need to get the content type manually! 
        var contentType = await mediator.Send(new GetContentTypeCommand { Id = item.ContentTypeId });
        
        var valuesInDict = item.PropertyData.ToDictionary(x => x.ContentTypePropertyId, x => x);
        foreach (var p in contentType.ContentProperties.Where(x => x.IsRequired))
        {
            
            valuesInDict.TryGetValue(p.Id, out var contentValue);
            if (contentValue != null && contentValue.Value.IsNullOrWhiteSpace())
            {
                validateResult.ErrorMessages.Add($"{p.Name} is required");
            }
        }

        return validateResult;
    }
}

Any issues, you just add an error message to the ErrorMessages list and those are displayed to the editor. They will be unable to continue until these are addressed

Last updated