3

我有一个有属性的模型

    [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)
    {
       ???????
    }
}

谢谢。

4

2 回答 2

3

您可以使用CountAny

   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();
       }
    }
于 2013-06-25T09:16:20.510 回答
1

实际上,您的方法具有价值:

public override bool IsValid(object value)
{
    var phoneNumbers = value as List<Phone>;
    if(phoneNumbers != null) 
    {
        // perform the validation
    }
}
于 2013-06-25T09:26:22.423 回答