4

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 ?

Nikos
  • 43
  • 1
  • 6
  • What criteria must the list satisfy? You will probably need to create your own data annotation attribute – DGibbs Jul 03 '13 at 13:52

2 Answers2

9

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; }
DGibbs
  • 14,316
  • 7
  • 44
  • 83
1

On top of what @DGibbs has specified if you want to perform client side validation you need to inherit IClientValidatable interface in custom class attribute and overriding GetClientValidationRules method. This will register client script like JavaScript function and the parameters within those methods. Please see this example and this

Sandeep Pote
  • 161
  • 8