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()
{
}
}
Have you looked into the following package for integrating FluentValidation into an ASP.NET Core application?
I believe this will include the necessary extension method(s) to allow you to register FluentValidation as the service you want to leverage for performing validation.
You can use this git Issues:
ASP.NET Core Razor Pages - validator for PageModel not invoked, even though validators for properties are invoked properly #887
https://github.com/FluentValidation/FluentValidation/issues/887
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.