Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Set Data Annotation on List<string> [duplicate]

I have this piece of code:

[Required]
public List<string> myStringList { get; set; }

Unfortunatelly, it doesn't work, tha validator totally ignores it.

Besides, this works fine:

[Required]
public string myString { get; set; }

and DateTimes work fine as well. Obviously, the problem doesn't lie on my validator, but on the annotation. So the question is, how should I set the Data Annotation on my list ?

like image 478
Nikos Avatar asked Mar 24 '23 07:03

Nikos


1 Answers

Create your own data annotation attribute, crude example:

public class ListHasElements : ValidationAttribute
{
   public override bool IsValid(List mylist)
   {
      if(mylist == null)
         return false;

      return mylist.Any();   
   }
}

Then use it like:

[ListHasElements(ErrorMessage = "List must contain an element")]
public List<string> myStringList { get; set; }
like image 188
DGibbs Avatar answered Mar 26 '23 21:03

DGibbs