带有DataAnnotations的MVC模型验证 - 是否需要进行ICollection的任何方法?

时间:2012-02-01 05:45:37

标签: asp.net-mvc-3 data-annotations

我在Model类中有一个属性,如:

    /// <summary>
    /// A list of line items in the receipt
    /// </summary>      
    public ICollection<ReceiptItem> Items { get; set; }

有什么方法可以标记此属性以验证集合是否必须包含1个或更多成员?我试图避免在ModelState.IsValid

之外的手动验证函数调用

3 个答案:

答案 0 :(得分:9)

我最后通过使用自定义DataAnnotation来解决问题 - 没想到看是否可以先完成!

这是我的代码,如果它可以帮助其他人!

/// <summary>
/// Require a minimum length, and optionally a maximum length, for any IEnumerable
/// </summary>
sealed public class CollectionMinimumLengthValidationAttribute : ValidationAttribute
{
    const string errorMessage = "{0} must contain at least {1} item(s).";
    const string errorMessageWithMax = "{0} must contain between {1} and {2} item(s).";
        int minLength;
        int? maxLength;          

        public CollectionMinimumLengthValidationAttribute(int min)
        {
            minLength = min;
            maxLength = null;
        }

        public CollectionMinimumLengthValidationAttribute(int min,int max)
        {
            minLength = min;
            maxLength = max;
        }

        //Override default FormatErrorMessage Method  
        public override string FormatErrorMessage(string name)
        {
            if(maxLength != null)
            {
                return string.Format(errorMessageWithMax,name,minLength,maxLength.Value);
            }
            else
            {
                return string.Format(errorMessage, name, minLength);
            }
        }  

    public override bool IsValid(object value)
    {
        IEnumerable<object> list = value as IEnumerable<object>;

        if (list != null && list.Count() >= minLength && (maxLength == null || list.Count() <= maxLength))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}
}

答案 1 :(得分:4)

在模型类中实现IValidatableObject接口,并在Validate方法中添加自定义验证逻辑。

public class MyModel : IValidatableObject
{
    public ICollection<ReceiptItem> Items { get; set; }

    public virtual IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (Items == null || Items.Count() == 0)
        {
            var validationResult = 
             new ValidationResult("One or more items are required") { Members = "Items"};
            return new List<ValidationResult> { validationResult };
        }

        return new List<ValidationResult>();
    }
}

答案 2 :(得分:2)

使用EF4 CodeFirst(EntityFramework.dll),您现在可以在阵列/列表/集合中使用 MinLengthAttribute MaxLengthAttribute

描述:指定属性中允许的最小数组/字符串数据长度。