gpt4 book ai didi

c# - 字符串集合的 FluentValidation

转载 作者:行者123 更新时间:2023-11-30 15:58:19 25 4
gpt4 key购买 nike

我有以下代码:

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 声明为列表。

我的单元测试:

    [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?

但我真的不明白我做错了什么。

最佳答案

检查这个例子,它可能会澄清你所有的疑虑。

验证类:

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

}



}

关于c# - 字符串集合的 FluentValidation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43523214/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com