3

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

Community
  • 1
  • 1
tobiak777
  • 3,175
  • 1
  • 32
  • 44

2 Answers2

0

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.

tobiak777
  • 3,175
  • 1
  • 32
  • 44
0

You could try something like this:

actual.ShouldBeEquivalentTo(expected, config=>  config.Excluding(s => s.TimeStamp), "because they should be similar");
andrew pate
  • 3,833
  • 36
  • 28