How to use FormHelper and FluentValidation in .netcore 6 razor pages

Viewed 234

I am moving away from mvc to razor pages but can't seem to find my way around with the validation using fluent validator and FormHelper.

Normally with the mvc pattern

[FormValidator]
Public async Task<IActionResult> submitFormAction()
{
    // do something 
    return View();
}

With Razor page

 public class AddModel : PageModel
 {
     public void OnGet()
     {

     }

     [FormValidator] // *'FormValidator' cannot be applied to razor page handler method it may be applied to either Razor page model or applied globally* 
     public async Task OnPostAsync()
     {
         
     }
 }
3 Answers

For anyone else facing the same issue.

The problem is with FluentValidation, in previous version .netcore you could register the FluentValidation service by simply

service.AddFluentValidation(config => config.RegisterValidatorsFromAssemblyContaining<StartUp>());

with the code above .netcore uses reflection to register all the classes in StartUp.cs assembly that inherits AbstractValidator<T>

but with the .netcore 6, i had to still use the code above but replaced the Startup with Program as .netcore 6 doesn't make use of StartUp.cs and still had to implicitly register the validation services

builder.Services.AddTransient<IValidator<SomeClass>, SomeClassValidator>();

This works for me but i have a feeling it could be simplified more because if am working on a large app and i have upto 20 validators my Program.cs won't be maintainable

PS: the [FormValidator] on the action method is obsolete as using the asp-FormHelper="true" tag helper along is okay

Related