使用 DataAnnotations 进行 MVC 模型验证——有什么方法可以使 ICollection 成为必需的吗?

发布于 2025-01-01 10:14:15 字数 293 浏览 0 评论 0原文

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

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

有什么方法可以标记此属性来验证集合必须有 1 个或多个成员吗?我试图避免在 ModelState.IsValid 之外进行手动验证函数调用

I have a property in a Model class something like:

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

Is there any way I can mark up this property to validate that the collection must have 1 or more members? I am trying to avoid a manual validation function call outside of ModelState.IsValid

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

|煩躁 2025-01-08 10:14:15

我最终通过使用自定义 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;
        }
    }
}
}

I ended up solving the problem by using a custom DataAnnotation -- did not think to see if this could be done first!

Here is my code if it helps anyone else!

/// <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;
        }
    }
}
}
千仐 2025-01-08 10:14:15

在模型类中实现 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>();
    }
}

Implement IValidatableObject interface in your model class and add the custom validation logic in Validate method.

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>();
    }
}
〆凄凉。 2025-01-08 10:14:15

借助 EF4 CodeFirst (EntityFramework.dll),您现在可以在数组/列表/集合上使用 MinLengthAttributeMaxLengthAttribute

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

With the EF4 CodeFirst (EntityFramework.dll), you now have MinLengthAttribute and MaxLengthAttribute that you can use on array/list/collection.

Description: Specifies the minimum length of array/string data allowed in a property.

微暖i 2025-01-08 10:14:15

实现此目的的最简单方法是在数据模型或 DTO 中使用 MinLength DataAnnotation

[MinLength(1, ErrorMessage = "Please provide at least an item")]
public ICollection<ReceiptItem> Items { get; set; }

The simplest way to achieve this is to use the MinLength DataAnnotation in your Data Model or DTOs

[MinLength(1, ErrorMessage = "Please provide at least an item")]
public ICollection<ReceiptItem> Items { get; set; }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文