Search code examples
c#asp.net-mvcfluentvalidation

FluentValidation ModelState.IsValid always true


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");
    }

Solution

  • 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