Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FluentValidation: arguments in the Validator constructor

I am using the FluentValidation package in my ASP.net project. I would like to know how to pass a parameter to the Validator constructor.

Here is what I would like to do with my validator. Notice the string MsgParam in the constructor:

public class RegisterModelValidator : AbstractValidator<RegisterModel>
{
    public RegisterModelValidator(string MsgParam) // <= Here
    {
        RuleFor(x => x.UserName)
            .NotNull()
            .WithMessage(MsgParam);
        RuleFor(x => x.Password)
            .NotNull()
            .Length(6, 100);
        RuleFor(x => x.ConfirmPassword)
            .Equal(x => x.Password);
    }
}

And my model, where I do not know if I can pass anything using data annotation:

// Find a way to pass a string to the validator
[FluentValidation.Attributes.Validator(typeof(RegisterModelValidator))]
public class RegisterModel
{
    public string UserName { get; set; }

    [DataType(DataType.Password)]
    public string Password { get; set; }

    [DataType(DataType.Password)]
    public string ConfirmPassword { get; set; }
}

Is it possible to do such a thing?

like image 603
Andreas Schwarz Avatar asked Sep 10 '25 18:09

Andreas Schwarz


1 Answers

In case someone arrives to this page, I was able to (partially) solve the problem thanks to JeremyS on the official FluentValidation page.

Be aware that with this solution, the client-side validation unfortunately disappears!

To take parameters in the validator constructor you need to instantiate it manually instead of relying on automatic creation.

The RegisterModel becomes:

public class RegisterModel
{
    public string UserName { get; set; }

    [DataType(DataType.Password)]
    public string Password { get; set; }

    [DataType(DataType.Password)]
    public string ConfirmPassword { get; set; }
}

And the Register method in the controller needs to be modified like this:

using FluentValidation.Mvc;
...
public ActionResult Register(RegisterModel model)
{
    RegisterModelValidator rmv = new RegisterModelValidator("Message passed as param");
    var result = rmv.Validate(model);

    if (result.IsValid)
    {
        // Here you decide what to do if the form validates
    }
    else
    {
        result.AddToModelState(ModelState, null);
    }
    return View(model);
}
like image 98
Andreas Schwarz Avatar answered Sep 13 '25 11:09

Andreas Schwarz