Array must contain 1 element

CallumVass picture CallumVass · Nov 13, 2012 · Viewed 20.2k times · Source

I have the following class:

public class CreateJob
{
    [Required]
    public int JobTypeId { get; set; }
    public string RequestedBy { get; set; }
    public JobTask[] TaskDescriptions { get; set; }
}

I'd like to have a data annotation above TaskDescriptions so that the array must contain at least one element? Much like [Required]. Is this possible?

Answer

Sat picture Sat · May 19, 2013

It can be done using standard Required and MinLength validation attributes, but works ONLY for arrays:

public class CreateJob
{
    [Required]
    public int JobTypeId { get; set; }
    public string RequestedBy { get; set; }
    [Required, MinLength(1)]
    public JobTask[] TaskDescriptions { get; set; }
}