字符串集合的FluentValidation

3
我有以下代码:
public partial class CustomerContactCommunicationValidator : AbstractValidator<CustomerCommunication>
{
    public CustomerContactCommunicationValidator()
    {
       CascadeMode = CascadeMode.StopOnFirstFailure;

        RuleFor(x => x.PhoneNumbers).SetCollectionValidator(new FaxPhoneNumberValidator("PhoneNumber"));
        RuleFor(x => x.FaxNumbers).SetCollectionValidator(new FaxPhoneNumberValidator("Faxnumbers"));
    }               
}

public class FaxPhoneNumberValidator : AbstractValidator<string>
{
    public FaxPhoneNumberValidator(string collectionName)
    {
        RuleFor(x => x).Length(0, 35).OverridePropertyName(collectionName);
    }
}

电话号码和传真号码被声明为列表。
我的单元测试:
    [TestMethod]
    [TestCategory("ValidationTests")]
    public void ShouldHaveErrorWhenPhoneNumberIsLongerThan35Charachters()
    {
        validator.ShouldHaveValidationErrorFor(x => x.PhoneNumbers, new List<string>() { "123456789012345678901234567890123456111" });
    }

    [TestMethod]
    [TestCategory("ValidationTests")]
    public void ShouldNotHaveErrorWhenPhoneNumberIsSmallerThan35Charachters()
    {
        validator.ShouldNotHaveValidationErrorFor(x => x.PhoneNumbers, new List<string>() { "0032486798563" });
    }

第一个测试失败了,第二个测试没有。同时,当我进行实时测试时,它成功地验证了一个超过35个字符的电话号码。
我看到了其他关于此问题的问题:如何使用Fluent Validation对列表中的每个字符串进行验证? 但我真的不知道我做错了什么。

你好,你尝试过下面的代码吗?它对你也有效吗? - Giovanni Romio
2个回答

2

尝试使用:

public class CustomerContactCommunicationValidator : AbstractValidator<CustomerCommunication>
{
   public CustomerContactCommunicationValidator()
   {
       RuleForEach(x => x.PhoneNumbers).Length(0, 35);
       RuleForEach(x => x.FaxNumbers).Length(0, 35);
   }
}

2

请查看这个示例,它可能会澄清你所有的疑问。

验证类:

using FluentValidation;
using System.Collections.Generic;

namespace Test.Validator
{

    public class EmailCollection
    {
        public IEnumerable<string> email { get; set; }

    }

    public class EmailValidator:  AbstractValidator<string>
    {
        public EmailValidator()
        {
            RuleFor(x => x).Length(0, 5);
        }

    }

    public class EmailListValidator: AbstractValidator<EmailCollection>
    {
        public EmailListValidator()
        {
            RuleFor(x => x.email).SetCollectionValidator(new EmailValidator());
        }

    }



}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接