Can I add more than one validator to an object? For example:
public interface IFoo
{
int Id { get; set; }
string Name { get; set; }
}
public interface IBar
{
string Stuff { get; set; }
}
public class FooValidator : AbstractValidator<IFoo>
{
public FooValidator ()
{
RuleFor(x => x.Id).NotEmpty().GreaterThan(0);
}
}
public class BarValidator : AbstractValidator<IBar>
{
public BarValidator()
{
RuleFor(x => x.Stuff).Length(5, 30);
}
}
public class FooBar : IFoo, IBar
{
public int Id { get; set; }
public string Name { get; set; }
public string Stuff { get; set; }
}
public class FooBarValidator : AbstractValidator<FooBar>
{
public FooBarValidator()
{
RuleFor(x => x)
.SetValidator(new FooValidator())
.SetValidator(new BarValidator());
}
}
Running the test.
FooBarValidator validator = new FooBarValidator();
validator.ShouldHaveValidationErrorFor(x => x.Id, 0);
I get an InvalidOperationException
:
Property name could not be automatically determined for expression x => x. Please specify either a custom property name by calling 'WithName'.
Is there any way to implement this or am I trying to use FluentValidation in a way that it's not meant to be used?