オブジェクトに複数のバリデータを追加できますか? 例えば:
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());
}
}
テストを実行しています。
FooBarValidator validator = new FooBarValidator();
validator.ShouldHaveValidationErrorFor(x => x.Id, 0);
私は得るInvalidOperationException
:
式 x => x のプロパティ名を自動的に決定できませんでした。「WithName」を呼び出してカスタム プロパティ名を指定してください。
これを実装する方法はありますか、それとも意図しない方法で FluentValidation を使用しようとしていますか?