Search code examples
c#asp.netasp.net-coreasynchronouscustom-attributes

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


Solution

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