Question

I'm using the library servicestack, and I have a problem using the library ServiceStack.FluentValidation.Mvc3, I followed the steps to configure this library, to make the asp.net mvc engine recognises Model.IsValid property, but this was always true. Here a snippet of code for validations settings that I have in my application.

public class AppHost: AppHostBase
{
    public AppHost() : base("Api Services", typeof(AppHost).Assembly)
    {
    }
    //Provide extra validation for the registration process
    public class CustomRegistrationValidator : RegistrationValidator
    {
        public CustomRegistrationValidator()
        {
            RuleSet(ApplyTo.Post, () =>
            {
                RuleFor(x => x.DisplayName).NotEmpty().WithMessage("Ingresa tu nombre de usuario");
                RuleFor(x => x.LastName).NotEmpty().WithMessage("Ingresa tu apellido");
                RuleFor(x => x.Name).NotEmpty().WithMessage("Ingresa tu nombre");
            });
        }
    }

    public class CustomAuthValidator : AbstractValidator<Auth>
    {
        public CustomAuthValidator()
        {
            RuleFor(x => x.UserName).NotEmpty().WithMessage("Ingresa tu nombre de usuario").WithName("Nombre de Usuario");
            RuleFor(x => x.Password).NotEmpty().WithMessage("Ingresa tu contraseña").WithName("Contraseña");
        } 
    }
    public override void Configure(Container container)
    {
        container.Adapter = new WindsorContainerAdapter();

        Plugins.Add(new AuthFeature(() => new AuthUserSession(), new IAuthProvider[] {
            new CredentialsAuthProvider(),    
            new BasicAuthProvider()}));


        Plugins.Add(new RegistrationFeature());
        Plugins.Add(new ValidationFeature());

        container.RegisterAs<CustomRegistrationValidator, IValidator<Registration>>();
        container.RegisterAs<CustomAuthValidator, IValidator<Auth>>();

        FluentValidationModelValidatorProvider.Configure();

        container.Register<IRedisClientsManager>(c => new PooledRedisClientManager("localhost:6379"));
        container.Register(c => c.Resolve<IRedisClientsManager>().GetCacheClient()).ReusedWithin(Funq.ReuseScope.None);

        container.Register<IResourceManager>(new ConfigurationResourceManager());



        ControllerBuilder.Current.SetControllerFactory(new FunqControllerFactory(container));
        ServiceStackController.CatchAllController = reqCtx => container.TryResolve<AccountController>();

    }


    public static void Start()
    {
        new AppHost().Init();
    } 
}

the message errors are the default ones does not change the name of the labels that I had set in the code that shows up.

Here is the extract of the code to see if the model is valid or not, into of controller Account.

[HttpPost]
public ActionResult LogOn(Auth model, string returnUrl)
{
    //This always is true
    if (ModelState.IsValid)
    {
        //TODO: Save database and other action more
    }
    return View(model);
}

Please help.

Was it helpful?

Solution

This should work, though I don't know if it's the best solution

Subclass Auth and attribute it with ValidatorAttribute

[Validator(typeof(CustomAuthValidator))]
public class MyAuth : Auth
{
}

Change your CustomAuthValidator to use the new MyAuth type

public class CustomAuthValidator : AbstractValidator<MyAuth>
{
    public CustomAuthValidator()
    {
        RuleFor(x => x.UserName).NotEmpty().WithMessage("Ingresa tu nombre de usuario").WithName("Nombre de Usuario");
        RuleFor(x => x.Password).NotEmpty().WithMessage("Ingresa tu contraseña").WithName("Contraseña");
    }
}

Change your controller to take the new MyAuth type

[HttpPost]
public ActionResult LogOn(MyAuth model, string returnUrl)
{
    //This should now work as expected
    if (ModelState.IsValid)
    {
        //TODO: Save database and other action more
    }
    return View(model);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top