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.)
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.
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.
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