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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With