Validation rule for Media

Geo Neeliyara asked on February 22, 2022 10:15

Hi

I would like to add required field validation on Image field. I used the below code and have annotation "Required". Annotation works fine with text field. Do I miss any other setting. I am using Kentico 13 MVC (v13.0.49)

Code
/// <summary>
    /// Guid of background image.
    /// </summary>
    [EditingComponent(MediaFilesSelector.IDENTIFIER, Label = "Content Widget Image (700 x 530)", Order = 3)]
    [EditingComponentProperty(nameof(MediaFilesSelectorProperties.LibraryName), MEDIA_LIBRARY_NAME)]
    [EditingComponentProperty(nameof(MediaFilesSelectorProperties.MaxFilesLimit), 1)]
    [EditingComponentProperty(nameof(MediaFilesSelectorProperties.AllowedExtensions), ".gif;.png;.jpg;.jpeg")]
    [Required]
    public IEnumerable<MediaFilesSelectorItem> Image { get; set; } = Enumerable.Empty<MediaFilesSelectorItem>();

Regards, Geo

Correct Answer

Arjan van Hugten answered on February 22, 2022 10:39

We used a custom validation attribute to validate that the collection does contain at least x item(s).

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter)]
public class MinimumCollectionLengthAttribute : ValidationAttribute
{
    private readonly int minimumLength;

    public MinimumCollectionLengthAttribute(int minimumLength)
    {
        this.minimumLength = minimumLength;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var collection = value as ICollection;
        if (collection is null)
        {
            return GetFailedResult(validationContext);
        }

        return collection.Count >= minimumLength ? 
            ValidationResult.Success
            : GetFailedResult(validationContext);
    }

    private ValidationResult GetFailedResult(ValidationContext validationContext)
    {
        return string.IsNullOrWhiteSpace(ErrorMessage) ?
            new ValidationResult($"The {validationContext.DisplayName} field is required.")
            : new ValidationResult(ErrorMessage);
    }
}

The usage is of the attribute is specified like this:

[MinimumCollectionLength(1)]

1 votesVote for this answer Unmark Correct answer

Recent Answers


Geo Neeliyara answered on February 22, 2022 10:57

Many thanks Arjan..Much appreciated..

0 votesVote for this answer Mark as a Correct answer

   Please, sign in to be able to submit a new answer.