3

I have the following code:

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 and FaxNumbers are declared as List.

My unit tests:

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

The first test fails, the second one does not. Also when I do a live test, it succeeds on a phone number which is larger than 35 charachters.

I've seen other questions about this: How do you validate against each string in a list using Fluent Validation?

But I really don't see what I'm doing wrong.

Community
  • 1
  • 1
CyclingFreak
  • 1,614
  • 2
  • 21
  • 40

2 Answers2

2

Check this example it might clarify all your doubts.

Validation classes:

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

    }



}
Giovanni Romio
  • 1,008
  • 1
  • 11
  • 30
2

Try to use:

public class CustomerContactCommunicationValidator : AbstractValidator<CustomerCommunication>
{
   public CustomerContactCommunicationValidator()
   {
       RuleForEach(x => x.PhoneNumbers).Length(0, 35);
       RuleForEach(x => x.FaxNumbers).Length(0, 35);
   }
}
R.Titov
  • 3,115
  • 31
  • 35