4

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?

1 Answer 1

4

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.