Use async method in custom validation attribute in c#

I have an async method that evaluates a field.

Task<bool> MyMethod(object obj);

I want to create a custom validation attribute that uses the above method.
My problem is that the ValidationAttribute class does not support async methods.

I usually override the following method:

ValidationResult IsValid (object? obj, ValidationContext validationContext);

But the output of my async method is Task<ValidationResult> and I don’t want to use synchronous method.

Do you have a solution or suggestion?

Tip: I want to use the async method because of I/O blocking. (No CPU bound or heavy operations.)

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Use async method in custom validation attribute

The validation pipeline is not asynchronous, so it’s not possible to be used for this purpose. See this similar thread.

Besides, as we all know, Validation is about ensuring type and value correctness, not business rules such as evaluating a field. That should be enforced in your business/data layer, and you could try to use JQuery validation or Remote attribute.

Method 2

You are going to have to choose then, if the ValidationAttribute doesn’t support async/await calls then you may have to go synchronous, otherwise you could have a call in your IsValid to an async method, but then it wouldn’t block and you may get an incorrect result.

I do not see any way around this as you will need to know almost immediately if something is valid or invalid. This is probably the reason the ValidationAttribute doesn’t recognise them.

You could modify your model rather than extending, and have an isValidChecked event or isInvalid event that fire from change of details from an async then do something when those events fire.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x