Fluent Validation and Inheritance
Fluent Validation and Inheritance

Demo – Inheritance Validation using Fluent Validations

Many times the object has a property which allows various implementations of the same interface. Or sometimes, the collection of a given interface may have objects of different types which implement that interface. This article provides information about how to validate such objects using Fluent Validation.

Scenario

Lets take a hypothetical scenario where an organization needs to store the details about a person. A person may be an employee from the organization or the person may also be a consultant which is hired on contract for specific period of time.

Let’s say there is an application to save this information. This application has a method which takes an input parameter “SavePersonRequest” which can contain either employee detail or the consultant details.

The interfaces / classes are shown in the code snippet given below.

Project Setup

Let’s create an Console Application project. In this project, let’s add the package FluentValidation to the project.

Inheritance and Validators

Let’s try to add validators now. Adding validators for Employee and Consultant class is easy. These validators are shown in the code snippet given below.

Now, the question is how to validate SavePersonRequest as it may contain either Employee details or Consultant details ?

For that, we need to ensure that EmployeeValidator should be called if the SavePersonRequest contains employee details and ConsultantValidator should be called if the SavePersonRequest contains consultant details. Fluent validation provides a method SetInheritanceValidator which can be used for this purpose.

This method takes a function as parameter, and this function can be used to define the child validators.

In the code snippet given below, we have called SetInheritanceValidator while setting validation rule for Person property. Then we passed a function to this method, this function calls Add method to pass the employee validators and consultant validators.

Run and Verify

For testing the above mentioned validators, we will need to create two requests – one containing employee details and other containing consultant details. Then we will trigger the request validator and check if it appropriately picks up the validator.

The code given below shows the code that I have added to the Main method of the console application that we created. It also shows the SavePerson method, which is triggering the validation.

Now, If I run the application I can see that both validation has failed. From the error messages given in the snapshot given below, we can understand that appropriate validator was picked up by the fluent validation.

I hope you find this information helpful. Let me know your thoughts.

Leave a ReplyCancel reply