FluentValidation集合属性没有验证 [英] FluentValidation collection properties not validated

查看:494
本文介绍了FluentValidation集合属性没有验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我第一次试图实现FluentValidation因为我需要涵盖复杂的验证场景。

This is the first time I'm trying to implement FluentValidation since I need to cover a complex validation scenario.

我想验证类具有属性,复杂的对象和多个集合量大。

The class I'm trying to validate has a large quantity of properties, complex objects and several collections.

我没有烦恼,以验证主体类的属性,或者集合不为空,甚至检查,但我有问题,而每个集合中的验证对象的属性。

I didn't have troubles to validate properties of the main class or even checking if collections are not empty, but I do have problems while validating objects properties within each collection.

要实现这一点,我跟着这里记录的例子(下检查集合校验器重复使用):
HTTP://fluentvalidation.$c$cplex.com/wikipage标题= creatingavalidator

To implement this I followed the examples documented here (check under "Re-using Validators for Collections"): http://fluentvalidation.codeplex.com/wikipage?title=creatingavalidator

这是我的模型类(减少以提高可读性)

These are my model classes (reduced to improve readability)

public class Caso
{
public int Id { get; set; } 
public string Descripcion { get; set; }
public List<Medicamento> Medicamentos { get; set; }
}

public class Medicamento
{
public int Id { get; set; }
public string Nombre { get; set; }
}

这是校验器类:

public class CasoValidator : AbstractValidator<CasoAdverso>
{
    public CasoValidator()
    {
        RuleSet("Iniciar", () =>
        {
            // Validated OK
            RuleFor(x => x.Descripcion).NotEmpty();
            // Validated OK
            RuleFor(x => x.Medicamentos).Must(x => x != null && x.Count > 0).WithMessage("No puede iniciar un caso sin medicamentos cargados");
            RuleFor(x => x.Medicamentos).SetCollectionValidator(new MedicamentoValidator());
        });
    }
}

public class MedicamentoValidator : AbstractValidator<Medicamento>
{
    public MedicamentoValidator()
    {
        // NOT Validated. Even if the object property is empty the error message doesn't appear. I also checked using "NotNull" and "NotEmpty" clauses
        RuleFor(x => x.Nombre).NotNull().WithMessage("Debe especificar un nombre"); 
    }
}

(注意:我使用的,因为不同的验证模式这是依赖于工作流中的文档状态的规则集)

(Note: I'm using RuleSet because of different validation schemas which are dependent of the document status in the workflow)

我手动从控制器执行验证(无MVC集成)

I'm executing the validation manually from the controller (no MVC integration)

[HttpPost]
public ActionResult Iniciar(Caso c)
{
    CasoValidator validator = new CasoValidator();
    FluentValidation.Results.ValidationResult validate = validator.Validate(c, ruleSet: "Iniciar"); 


    // ...
}

随着主类的这种实现性能验证的罚款,但我也需要在集合中验证了Medicamento类的每个属性。

With this implementation properties of the main class are validated fine but I need also to validate each property of the "Medicamento" class within the collection.

我能在这里失去了一些东西?如果这种使用可用的RuleForEach条款被验证?

Could I be missing something here?. Should this be validated using the RuleForEach clause available?

任何帮助将AP preciated。

Any help will be appreciated.

推荐答案

它出现的规则集设置应用到子验证以及主之一。

It appears the RuleSet setting is applying to the child validator as well as the primary one.

我测试了code在xUnit.net测试,并确认它。

I tested your code in an xUnit.net test, and confirmed it.

如果你改变你的规则集来执行,你应该找到它按预期工作:

If you change your rulesets to execute you should find it works as expected:

CasoValidator validator = new CasoValidator();
FluentValidation.Results.ValidationResult validate = validator.Validate(c, ruleSet: "default,Iniciar");

在默认规则集将工作在MedicamentoValidator规则。

The 'default' ruleset will work on the MedicamentoValidator rules.

我不只有通过测试的文档中找到这个。

I didn't find this in the documentation, only through testing.

这是样品单元测试:

[Fact]
public void Test1()
{

    Caso c = new Caso()
    {
        Id = 1,
        Descripcion = "none",
        Medicamentos = new List<Medicamento>()
    };

    c.Medicamentos.Add(new Medicamento()
    {
        Id = 0,
        Nombre= null
    });

    CasoValidator validator = new CasoValidator();
    FluentValidation.Results.ValidationResult validate = validator.Validate(c, ruleSet: "default,Iniciar");

    Assert.NotEmpty(validate.Errors);
}

更新:我发现杰里米·斯金纳参考正是这种行为:
HTTP://fluentvalidation.$c$cplex.com/discussions/266920

规则集级联任何子验证,故取其规则集
  选择用于由顶层验证器使用也将被用于
  子验证。
       所以,如果你跑了最小规则集的CreateProfileModelValidator,那么只有在最小规则集规则
  将在的两个的的CreateProfileModelValidator并运行
  ProfileValidator。

Rulesets cascade to any child validators, so whichever ruleset is selected for use by the top-level validator will also be used by the child validator. So if you ran the "Minimal" ruleset on the CreateProfileModelValidator, then only rules in the "Minimal" ruleset will be run on both the CreateProfileModelValidator and the ProfileValidator.

这篇关于FluentValidation集合属性没有验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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