question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Validation message not showing (ASP.Net core + Autofac + FluentValidation)

See original GitHub issue

Hi there, I am working on ASP.Net Core application in which I want to do validation for the viewmodel. I cannot use [Validator] attribute on my viewmodel as they are in different assembly which I cannot reference to my Core assembly. My validator does work but when it returns the view back, it’s not showing any validation messages. I have all the jquery libraries configured and included, in fact it was working with data annotation attributes (ie. Required, EmailAddress etc.) and showing messages in the browser. Here is the code:

  1. WebApp.Core.dll
public class UserRegistrationViewModel
    {
        public string BusinessUnitName { get; set; }
        [DataType(DataType.Password)]
        public string ConfirmPassword { get; set; }
        [DataType(DataType.Password)]
        public string Password { get; set; }
        public string PrimaryUserEmail { get; set; }
        public string PrimaryUserName { get; set; }
    }
  1. WebApp.Business.dll
public sealed class UserRegistrationViewModelValidator :
AbstractValidator<UserRegistrationViewModel>
    {
        public UserRegistrationViewModelValidator(IEntitiesContext context)
        {
            RuleFor(vm => vm.BusinessUnitName)
                .NotEmpty();

            RuleFor(vm => vm.ConfirmPassword)
                .NotEmpty()
                .Equal(vm => vm.Password)
                .WithMessage(LocalizedStrings.ConfirmPasswordCompareErrorMessage);

            RuleFor(vm => vm.Password)
                .NotEmpty()
                .Length(6, 25);

            RuleFor(vm => vm.PrimaryUserEmail)
                .NotEmpty()
                .EmailAddress();

            RuleFor(vm => vm.PrimaryUserName)
                .NotEmpty()
                .Length(6, 50);
        }
    }
  1. WebApp.dll (Startup.cs)
services
    .AddMvc()
    .AddFluentValidation(fv =>
fv.RegisterValidatorsFromAssemblyContaining<UserRegistrationViewModelValidator>());
  1. WebApp.dll (UserController.cs)
[AllowAnonymous]
[ValidateAntiForgeryToken]
[HttpPost]
public async Task<IActionResult> Registration(UserRegistrationViewModel viewModel)
{
	if (!ModelState.IsValid)
	{
		return View(viewModel);
	}
	string UserUrl = Request.GetRootUrl();
	var result = await _mediator.Send(new InsertQuery<UserRegistrationDto>
	{
		Dto = new UserRegistrationDto
		{
			BusinessUnitName = viewModel.BusinessUnitName,
			Email = viewModel.PrimaryUserEmail,
			Name = viewModel.PrimaryUserName,
			Password = viewModel.Password,
			Url = UserUrl
		}
	});
	if (!result.Succeed)
	{
		foreach (var error in result.Errors)
		{
			ModelState.AddModelError("", error);
		}
		return View(viewModel);
	}
	var appUser = await _userManager.FindByEmailAsync(viewModel.PrimaryUserEmail).ConfigureAwait(false);
	await _signInManager.SignInAsync(appUser, true).ConfigureAwait(false);
	return RedirectToAction("Index", "Home");
}

I am not sure what is missing, I couldn’t find any example that shows the implementations I am looking for. Please note that I am using Autofac instead of default asp.not core IoC.

Thanks, Binoy

Issue Analytics

  • State:closed
  • Created 7 years ago
  • Comments:16 (9 by maintainers)

github_iconTop GitHub Comments

1reaction
JeremySkinnercommented, Jan 25, 2017

So this doesn’t look right to me:

services
    .AddMvc()
    .AddFluentValidation(fv =>
fv.RegisterValidatorsFromAssemblyContaining<UserRegistrationViewModelValidator>());

…that registers the validators with MVC’s built-in standard container. If you’re using autofac then I’d expect to see you registering a custom ValidatorFactory with FV that calls into autofac instead.

Have you already got an AutofactValidatorFactory written?

0reactions
binoypatelcommented, Jan 30, 2017

Thank you very much for detailed testing and provided the solution, I will test this and update you if it doesn’t work. It will be interesting to try new beta 😃

Read more comments on GitHub >

github_iconTop Results From Across the Web

Validation message not showing (ASP.Net core + Autofac ...
Hi there, I am working on ASP.Net Core application in which I want to do validation for the viewmodel. I cannot use [Validator]...
Read more >
FluentValidation decorator doesn't work with autofac and ...
in this class my code goes directly in public UserDomain Handle(GetUserByEmailQuery message) without doing validation. asp.net-core · autofac ...
Read more >
ASP.NET Core — FluentValidation documentation
With automatic validation, FluentValidation plugs into the validation pipeline that's part of ASP.NET Core MVC and allows models to be validated before a ......
Read more >
How To Easily Set Up Fluent Validation With Autofac
Configuring and using Fluent Validation and Autofac. ... 5.00/5 (2 votes) ... If there are, we re-display the form and show the errors....
Read more >
Fluent Validation in ASP.NET Core - no dogma blog
How to return to validation messages back to the caller is not immediately obvious. You might see the validators running, but the responses...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found