FluentValidation- More Scenarios

Avinash Karat
4 min readMar 5, 2021

Hi guys, this is going to be a part 2 of FluentValidation post. I had written a post about what fluentvalidation is, and how can we integrate the same into a .Net Core Web API solution in an earlier post. In case if you haven’t read that, I am putting a link to that here.

In this article I am going to cover some scenarios which might be useful in real world applications.

  1. Validating child objects

In the last post, I had shown how to validate a plain model class. That class was very basic, having a bunch of primitive value type properties alone. But in real world, a model might be containing properties which will be another class references. In this case, lets look at how can we validate the child class.

I have modified the Customer class to include a Product class’s reference. So now the changed model class looks like the below class:

and the Product class definition is shown below:

Now lets look at how can we modify the validator class so that when a request comes, it will validate the child class rules too. Basically here we have to use the .Setvalidator() property and pass the child validator class as the argument.

child validation rules are shown below:

Now I am issuing a POSTMAN request to test the changes. Here I didn’t provide the Product object itself.

So its throwing error for not providing the product object. Now lets check what happens if we provide an empty product object.

here we can see the child validator’s rules got fired.

And if we provide the child object’s values too, the request will get succeed.

2. Selectively turning off fluentvalidation

Suppose we have a controller which is having two API methods, and having the same data model object as input parameter. And we want to enable fluentvalidation for one API method, and turning it off for the next one. In this type of scenarios, we need to use something called a “RuleSet()” feature in fluentvalidation.

Lets look at the controller methods first.

Here I have two API methods, called “Save” and “Update”

here my requirement is that, I want to enable fluentvalidation for “Save” and I don’t need any validation for “Update”.

So I am going to use the RuleSet() feature in my validator:

for applying the ruleset() in the controller, we need to use the [CustomizeValidator(RuleSet = “RuleName”)] attribute:

Let’s check what happens if I issue a request to the Update method, without the rules we defined earlier.

Here we can see that the request got succeeded even though I didn’t provide any email or product details. That's the beauty of the RuleSet() attribute.

Conclusion:

Okay. That was it. Hope this post was useful.

Thanks for reading!

--

--

Avinash Karat

Working professionally as a full stack .Net developer . Also have a keen interest in personal productivity, meditation&personal finance. Here to share things.