Skip to main content

Asynchronous Validation with FluentValidation

How to invoke RESTful API asynchronously to validate model-property in ASP.Net Core

FluentValidation is a popular .NET library for building strongly-typed validation rules. It can be used to separate the validation logic from model classes, unlike the data annotations approach.

If you have not used FluentValidation in ASP.Net Core, I would recommend you read this post, before proceeding.

 

Now you know how to perform automatic basic validations in your models. However, in real-world applications, we have to implement complex validation logic as well.

In our example, we will validate a model called Applicant. While most of its properties require simple validations, there is one property called Country, which should be validated using a RESTful API. I use this endpoint for validating the country value.

 

 

I implement a country validator as below;

 

 

Please note that CountryValidatorinherits from AsyncValidatorBase (rather than PropertyValidator ) which handles the ShouldValidateAsync overload.

 

Finally, implement ApplicantValidator

 

 

We can achieve the same validation without implementing CountryValidator, by using a custom rule defined in ApplicantValidator with MustAsync.

 

RuleFor(m => m.Country).MustAsync(async (country, cancellation) => (
await restClient.GetAsync(
$"https://restcountries.eu/rest/v2/name/{country}?fullText=true"))
.IsSuccessStatusCode).WithMessage("Country name is not valid.");

 

It is up to you to decide which approach fits better with your design. ASP.Net’s automatic validation does not support asynchronous validations at the moment, and it doesn’t seem to be supported in the near future either.

Therefore you’d need to disable the automatic MVC integration and invoke the validator manually from within an asynchronous controller action.

 

var validator = new ApplicantValidator();
var result = await validator.ValidateAsync(applicant);

 

Try it out yourself! 

 

Further Reading - https://github.com/FluentValidation/FluentValidation/issues/413

                             https://github.com/dotnet/aspnetcore/issues/7573


LEAVE A COMMENT







POST COMMENTS


© 2020 Creative Software. All Rights Reserved | Privacy | Terms of Use