FluentValidation ModelState.IsValid always true

2019-08-07 17:19发布

问题:

Ok my problem is the modelvalidator from fluentValidation is not working in my project, and ModelState.IsValid is always true no matter the state of the validation, im using asp.net mvc 4, .net 4.5, thx in advance.

Global.asax

protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        AuthConfig.RegisterAuth();
        FluentValidationModelValidatorProvider.Configure();
    }

LoginViewModel

using FluentValidation.Attributes;

namespace ViewModel.Cuentas
{

 [Validator(typeof(LoginViewModel))]
 public class LoginViewModel
 {
    public string UserName { get; set; }
    public string Password { get; set; }
 }
}

LoginViewModelValidator

using FluentValidation;
using FluentValidation.Results;
namespace ViewModel.Cuentas.Validadores
{
    public class LoginViewModelValidator : AbstractValidator<LoginViewModel>
    {
        public LoginViewModelValidator()
        {
        RuleFor(x => x.UserName).NotEmpty().WithMessage("El Campo Usuario es Necesario");
        RuleFor(x => x.Password).NotEmpty().WithMessage("El Campo Usuario es Necesario");
        }
   }
}

and my account controller

   [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Login(LoginViewModel viewModel)
    {
        if (!ModelState.IsValid)
        {
            return View();
        }
        FormsAuthentication.SetAuthCookie(viewModel.UserName, false);
        if (!String.IsNullOrEmpty(returnUrl) && returnUrl != "/")
        {
            return Redirect(returnUrl);
        }
        return RedirectToAction("Enviar", "Cartas");
    }

回答1:

Your Validator attribute appears to have the wrong type. You have:

[Validator(typeof(LoginViewModel))]
public class LoginViewModel

The type argument should be your validator class - LoginViewModelValidator. So it would be like this:

[Validator(typeof(LoginViewModelValidator))]
public class LoginViewModel


回答2:

Addition to accepted answer: If user using Aspnet Core framework need to be registered as service in Statrup.cs ( under 'ConfigureServices' method)

services.AddTransient<IValidator<LoginViewModel>, LoginViewModelValidator>();

[Validator(typeof(LoginViewModelValidator))] filter may not work as expected.