字符串集合的FluentValidation

时间:2017-04-20 15:02:10

标签: c# fluentvalidation

我有以下代码:

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

PhoneNumbers和FaxNumbers被声明为List。

我的单元测试:

    [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个字符的电话号码上成功。

我已经看到了其他问题:How do you validate against each string in a list using Fluent Validation?

但我真的不知道自己做错了什么。

2 个答案:

答案 0 :(得分: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());
        }

    }



}

答案 1 :(得分:1)

尝试使用:

oplogObserveDriver