【问题标题】:Strange behaviour of fluentvalidation's SetCollectionValidatorfluentvalidation 的 SetCollectionValidator 的奇怪行为
【发布时间】:2017-11-01 12:57:31
【问题描述】:

在我的项目中,我使用的是 .net 的 FluentValidation。我应用此验证的类是这样的:

[Validation(typeof(InputValidator))]
public class Inputs
{
    public IEnumerable<string> MobileNos { get; set; }
}

InputValidator.cs 文件是这样的

public class InputValidator: AbstractValidator<Inputs>
{
    public BlockMobileInputsValidator()
    {
         RuleFor(x => x.MobileNos).Cascade(CascadeMode.StopOnFirstFailure).NotEmpty()
                .Must(x => x.Count() <= 100).WithMessage("List should not contain more than 100 mobile numbers.")
                .SetCollectionValidator(new MobileValidator());
    }
}

还有MobileValidator.cs

public class MobileValidator:AbstractValidator<string>
{
    public Mobilevalidator()
    {
        RuleFor(x => x).Matches("^[6789]\d{9}$").WithMessage("{PropertyValue} is not in correct mobile-number format");
    }
}

现在,当我将 {null,"7897897897"} 列表传递给 MobileNos of Input 类时,它没有给出任何错误,并且列表被接受以供进一步使用。 我无法理解这种奇怪的行为。 I also tried this

public class MobileValidator:AbstractValidator<string>
{
    public Mobilevalidator()
    {
        RuleFor(x => x).NotNull().Matches("^[6789]\d{9}$").WithMessage("{PropertyValue} is not in correct mobile-number format");
    }
}

但这也不适用于上述输入。

谁能告诉它为什么接受null 值?

【问题讨论】:

    标签: c# regex fluentvalidation


    【解决方案1】:

    我不知道为什么你的代码不起作用但是当你将InputValidator.cs更改为以下代码时,你可以得到想要的结果:

    using FluentValidation;
    using System.Linq;
    
    public class InputsValidator : AbstractValidator<Inputs>
    {
        public InputsValidator()
        {
            RuleFor(x => x.MobileNos).Cascade(CascadeMode.StopOnFirstFailure).NotEmpty()
                                     .Must(x => x.Count() <= 100).WithMessage("List should not contain more than 100 mobile numbers.");
            RuleForEach(x => x.MobileNos).NotNull().SetValidator(new MobileValidator());
        }
    }
    

    那么下面的测试就通过了:

    using FluentValidation;
    using Xunit;
    using System;
    using System.Collections.Generic;
    
    namespace test
    {
        public class InputsValidatorTests
        {
            [Fact]
            public void WhenContainsNull_ThenIsNotValid()
            {
                var inputs = new Inputs();
                inputs.MobileNos = new List<string>() { null, "7897897897" };
                var inputsValidator = new InputsValidator();
    
                var result = inputsValidator.Validate(inputs);
    
                Assert.False(result.IsValid);
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-16
      • 2015-02-03
      • 1970-01-01
      • 1970-01-01
      • 2021-06-08
      • 2015-07-20
      • 2010-10-03
      • 2021-07-12
      相关资源
      最近更新 更多