首页 > 其他分享 >Validating multiple properties with FluentValidation(FluentValidator多个相关属性校验)

Validating multiple properties with FluentValidation(FluentValidator多个相关属性校验)

时间:2023-04-24 16:36:30浏览次数:48  
标签:foo multiple repository FluentValidator FluentValidation instance Foo properties

Source link:

Validating multiple properties with FluentValidation | The Codetripper (wordpress.com)

public class FooBarRequestValidator : AbstractValidator<FooBarRequest>
{
    private readonly IRepository repository;

    public FooBarRequestValidator(IRepository repository)
    {
        this.repository = repository;

        RuleFor(x => x.Foo)
        .Must(NotAlreadyHaveABar)
        .WithMessage("You already have a bar for this foo.");
    }

    private bool NotAlreadyHaveABar(FooBarRequest instance, string foo)
    {
        return !repository.GetAll<FooBar>()
        .Any(x => x.Foo == foo && x.Bar == instance.Bar);
    }
}

The trick is using the overload of Must() that takes a Func<T, TProperty, bool> predicate: that gives you access to the whole instance for your validating pleasure. Here, in NotAlreadyHaveABar() I can access Bar even though the rule is for the Foo property.

标签:foo,multiple,repository,FluentValidator,FluentValidation,instance,Foo,properties
From: https://www.cnblogs.com/tylertang/p/17349954.html

相关文章