Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make FluentValidation ignore a property

I have the following View Model

public class MyViewModel
{
    public MyViewModelClassWithValidator MandatoryProperty {get; set;}
    public MyViewModelClassWithValidator OptionalProperty {get; set;}

    public class MyViewModelValidator : AbstractValidator<MyViewModel>
    {
        public MyViewModelValidator()
        {
            RuleFor(x=> x.MandatoryProperty) //...
            //No rule for property 2
        }
    }
}

I'm looking for a way to make the OptionalProperty ignored by FluentValidation. Here, the validation errors of Optional Property still get added to the ModelState.

This answer suggests either 1. to avoid reusing the child model, but this is not an option in my case, and 2. to delete the errors from the ModelState. Before writing a dirty class to get the ModelState from the HttpContext, I'd like to know if there's an other way I'm unaware of since the answer is old.

My objective is to keep the validation logic encapsulated in my ViewModels.

Thank you

like image 727
tobiak777 Avatar asked Sep 13 '25 02:09

tobiak777


1 Answers

Okay so I've found an easy work around. I've created an extension class with a ThreadStatic field holding a reference to the current controller. All my controllers derive from a base controller, so I just set the current controller in the constructor. Once I have the controller I also have the ModelState so problem fixed.

like image 118
tobiak777 Avatar answered Sep 14 '25 17:09

tobiak777