问题
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 ?
回答1:
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; }
回答2:
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
来源:https://stackoverflow.com/questions/17449651/c-sharp-set-data-annotation-on-liststring