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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With