Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass parameter to validator - fluent validation

I have a validator that I use for both an insert, and an update. One of the checks I do is to see if what is being inserted already exists. The code for the validator is:

public GrapeColourValidator(IGrapeRepository grapeRepository)
        {
            _grapeRepository = grapeRepository;

            RuleFor(x => x.Colour)
                .NotEmpty()
                .WithMessage("Colour is required")
                .MaximumLength(_maxLength)
                .WithMessage($"Colour cannot be more that {_maxLength} characters");

            RuleFor(x => x)
                .MustAsync(async (grapeColour, context, cancellation) =>
                {
                    return await GrapeColourExists(grapeColour.Colour).ConfigureAwait(false);
                })
                .WithMessage($"Grape colour already exists");
        }

        private async Task<bool> GrapeColourExists(string grapeColour)
        {
            var colourResult = await _grapeRepository.GetByColour(grapeColour).ConfigureAwait(false);
            return !colourResult.Any(x => x.Colour == grapeColour);
        }

The issue with this is that it runs for Update also, so the colour will definitely exists. What I want to do is pass a parameter, so I could do something like:

if(isInsert)
            {
                RuleFor(x => x)
                .MustAsync(async (grapeColour, context, cancellation) =>
                {
                    return await GrapeColourExists(grapeColour.Colour).ConfigureAwait(false);
                })
                .WithMessage($"Grape colour already exists");
            }

Is this possible?

like image 286
Keith Avatar asked Mar 01 '26 06:03

Keith


1 Answers

3 years too late, but for anyone wondering how to do this - you can use RootContextData https://docs.fluentvalidation.net/en/latest/advanced.html#root-context-data

var context = ValidationContext<yourTypeHere>(request);
context.RootContextData["IsUpdate"] = true;
validator.Validate(context);

and then in your validator you can get the IsUpdate value out of the context

context.RootContextData.TryGetValue("IsUpdate", out var IsUpdate)
like image 187
hooah Avatar answered Mar 03 '26 03:03

hooah