2017-11-01 11 views
1

私のプロジェクトでは、私はFluentValidation of .netを使用しています。私はこの検証は、このようなものである適用されているクラス:私はMobileNos of Inputクラスに{null,"7897897897"}リストを渡すときFluentvalidationのSetCollectionValidatorの奇妙な動作

[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"); 
    } 
} 

のようなものですそれは何のエラーも与えておらず、さらなる使用のためにリストが受け入れられる。 私はこの奇妙な動作を理解することができません。 I also tried this

しかしこれも上記の入力に対しては機能しません。

nullの値を受け入れる理由を教えていただけますか?

答えて

2

あなたのコードが動作しない理由を私は知らないが、あなたは以下のコードに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); 
     } 
    } 
}