我有一个属性
的模型 [Display(Name = "Phone")]
public List<Phone> PhoneNumbers { get; set; }
我想验证List应该大于0
建议代码。
/// <summary>
/// Atleast one phone number is required
/// </summary>
public sealed class DemographicPhoneNumberRequiredCheck : ValidationAttribute
{
public override bool IsValid(object value)
{
???????
}
}
感谢。
答案 0 :(得分:3)
您可以使用Count
或Any
:
public override bool IsValid(object value)
{
var PhoneNumbers = value as List<Phone>;
if (PhoneNumbers != null)
{
return PhoneNumbers.Count() > 0;
}
return false;
}
或者:
public override bool IsValid(object value)
{
var PhoneNumbers = value as List<Phone>;
if (PhoneNumbers != null)
{
return PhoneNumbers.Any();
}
}
答案 1 :(得分:1)
实际上你的方法中有价值:
public override bool IsValid(object value)
{
var phoneNumbers = value as List<Phone>;
if(phoneNumbers != null)
{
// perform the validation
}
}