验证C#中的列表 [英] Validating lists in C#

查看:81
本文介绍了验证C#中的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在使用 DataAnnotations 来验证我们的模型.

We're using DataAnnotations to validate our model.

我们模型的一个非常简化的版本是:

A very simplified version of our model is:

public class Model
{
    public List<Thing> Things;
}

public class Thing
{
    [Required]
    public string Name {get;set;}
}

现在,有趣的是,如果我创建一个没有名称的 Thing 并将其添加到模型中,我希望验证会失败,但会通过(震惊!).

Now, the funny thing is that if I create a Thing with no name and add it to the model, I would expect validation to fail, but it passes (shock horror!).

var model = new Model ();
var invalidThing = new Thing (); // No name would fail validation
model.Things.Add(invalidThing );

var validationContext = new ValidationContext(model);
var validationResults = new List<ValidationResult>();
var isValid = Validator.TryValidateObject(model, validationContext, validationResults, true);

Assert.False (isValid);  // This fails!

认为的原因是,当您验证模型时,它会验证每个属性,但会验证属性中的项目(如果是集合). Things 是未经验证的属性,因此可以通过(尽管它包含无效项).

I think the reason for this is that when you validate the model, it validates each property but not items in the property if it's a collection. Things is a property that has no validation, so it passes (despite the fact that it contains invalid item).

我们如何确保验证也可以验证集合属性中的项目?我可以使用一些现成的验证器吗?

How can we ensure that validation also validates items in collection properties? Is there some out-of-the-box validator I could use?

推荐答案

我已通过为集合创建一个自定义验证器来解决此问题,该集合用于检查每个项目的验证.简化的代码如下所示:

I have fixed this by creating a custom validator for collections that checks validation on each item. A simplified code would look like this:

public class ValidateEachItemAttribute : ValidationAttribute
{
    protected readonly List<ValidationResult> validationResults = new List<ValidationResult>();

    public override bool IsValid(object value)
    {
        var list = value as IEnumerable;
        if (list == null) return true;

        var isValid = true;

        foreach (var item in list)
        {
            var validationContext = new ValidationContext(item);
            var isItemValid = Validator.TryValidateObject(item, validationContext, validationResults, true);
            isValid &= isItemValid;
        }
        return isValid;
    }

    // I have ommitted error message formatting
}

现在以这种方式装饰模型将按预期工作:

Now decorating the model this way would work as expected:

public class Model
{
    [ValidateEachItem]
    public List<Thing> Things;
}

这篇关于验证C#中的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆