MVC3自定义验证

时间:2013-06-25 09:14:57

标签: c# .net asp.net-mvc asp.net-mvc-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)
    {
       ???????
    }
}

感谢。

2 个答案:

答案 0 :(得分: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();
       }
    }

答案 1 :(得分:1)

实际上你的方法中有价值:

public override bool IsValid(object value)
{
    var phoneNumbers = value as List<Phone>;
    if(phoneNumbers != null) 
    {
        // perform the validation
    }
}