c# - 如何将验证属性应用于集合中的对象?

标签 c# validation collections .net-4.5

基本上,如果我有一个对象集合,我如何将验证属性应用到集合中的每个项目(例如 MaxLengthAttribute)?

public class Foo
{
    public ICollection<string> Bars { get; set; }
}

例如,我如何确保 Bars 包含的字符串可验证最大长度为 256?

更新:

我了解如何将验证属性应用于单个属性,但问题是如何将其应用于集合中的对象。

public class Foo
{
    [StringLength(256)] // This is obvious
    public string Bar { get; set; }

    // How do you apply the necessary attribute to each object in the collection!
    public ICollection<string> Bars { get; set; }
}

最佳答案

我知道这个问题有点老了,但也许有人会来寻找答案。

我不知道将属性应用于集合项的通用方法,但对于特定的字符串长度示例,我使用了以下方法:

public class StringEnumerationLengthValidationAttribute : StringLengthAttribute
{
    public StringEnumerationLengthValidationAttribute(int maximumLength)
        : base(maximumLength)
    { }

    public override bool RequiresValidationContext { get { return true; } }
    public override bool IsValid(object value)
    { return false; }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var e1 = value as IEnumerable<string>;
        if (e1 != null) return IsEnumerationValid(e1, validationContext);
        return ValidationResult.Success; // what if applied to something else than IEnumerable<string> or it is null?
    }

    protected ValidationResult IsEnumerationValid(IEnumerable<string> coll, ValidationContext validationContext)
    {
        foreach (var item in coll)
        {
            // utilize the actual StringLengthAttribute to validate the items
            if (!base.IsValid(item) || (MinimumLength > 0 && item == null))
            {
                return new ValidationResult(base.FormatErrorMessage(validationContext.DisplayName));
            }
        }
        return ValidationResult.Success;
    }
}

申请如下,要求每个收藏品4-10个字符:

[StringEnumerationLengthValidation(10, MinimumLength=4)]
public ICollection<string> Sample { get; set; }

关于c# - 如何将验证属性应用于集合中的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14097474/

相关文章:

集合中的 Java 过滤

java - 在 Spring-Hibernate 项目中初始化实体集合 (POJO) 的正确方法是什么?

c# - 如何从 .NET 应用程序使用 WinFax Pro COM 对象?

c# - 在 Application_AquireRequestState 事件中用 POST 数据重写 Url

c# - 围绕执行相同检查的多个 if 语句的代码重构 C# 问题

javascript下拉验证

c# - Process.Start ("name.exe") - 如何找到 'name.exe'?

xml - Eclipse xml 验证

javascript - Asp.net jQuery 验证引擎提交问题

unit-testing - 为什么 NUnit 没有 IsElementOf/IsOneOf 约束?