Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to await method in PropertyValidator's overridden IsValid?

I'm trying to use my Data Repository in PropertyValidator class. The problem is that method in the Repository is async... and I can't see IsValidAsync to override.

using System.Collections.Generic;
using System.Threading.Tasks;
using FluentValidation.Validators;
using AccountApi.Domain.Repositories;

namespace AccountApi.Domain.Validators
{
    public class UserInputValidator<TElement> : PropertyValidator
    {
        private IUserRepository _userRepository;

        public UserInputValidator(IUserRepository userRepository)
            : base("{Message}.")
        {
            _userRepository = userRepository;
        }

        protected override bool IsValid(PropertyValidatorContext context)
        {
            var id = (int)context.PropertyValue;
            var user = await _userRepository.GetById(id); // <--- HERE is the problem  

            // ..... 

            return true;
        }
    }
} 

I tried to change to this:

protected override async Task<bool> IsValidAsync(PropertyValidatorContext context)   

... but it doesn't work as well. There is no IsValidAsync to override.

Is it possible to use async methods inside PropertyValidator?

like image 569
Ish Thomas Avatar asked Jan 23 '26 15:01

Ish Thomas


1 Answers

You're sort of on the right track.

Yes, you do overload the PropertyValidator method protected virtual async Task<bool> IsValidAsync(PropertyValidatorContext context, CancellationToken cancellation)

However you need to use the validator.ValidateAsync(objectToValidate) method to use it.

If your validator contains asynchronous validators or asynchronous conditions, it’s important that you always call ValidateAsync on your validator and never Validate. If you call Validate, then your asynchronous rules will be run synchronously, which is not desirable.

Source

Additionally refer to the following issue where Jeremy suggests:

  • Also overloading the ShouldValidateAsync method; or better still
  • Use the AsyncValidatorBase rather than PropertyValidator which handles the ShouldValidateAsync overload for you

See the following if you want to see a working solution of an async property validator.

like image 77
rgvlee Avatar answered Jan 26 '26 05:01

rgvlee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!