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.