Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array must contain 1 element

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?

like image 819
CallumVass Avatar asked Nov 13 '12 13:11

CallumVass


2 Answers

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; } } 
like image 154
Sat Avatar answered Sep 23 '22 05:09

Sat


I've seen a custom validation attribute used for this before, like this:

(I've given sample with a list but could be adapted for array or you could use list)

public class MustHaveOneElementAttribute : ValidationAttribute {     public override bool IsValid(object value)     {         var list = value as IList;         if (list != null)         {             return list.Count > 0;         }         return false;     } }  [MustHaveOneElementAttribute (ErrorMessage = "At least a task is required")] public List<Person> TaskDescriptions { get; private set; }  // as of C# 8/9 this could be more elegantly done with      public class MustHaveOneElementAttribute : ValidationAttribute {     public override bool IsValid(object value)     {         return value is IList {Count: > 0};     } } 

Credit to Antonio Falcão Jr. for elegance

like image 41
dove Avatar answered Sep 24 '22 05:09

dove