Fluent Validations - Collections
Fluent Validations - Collections

ASP .NET Core API – Fluent Validations – Collections

In previous articles, we have discussed how to add fluent validations to the API project, we have seen how placeholders can be used and how error messages can be customized.

Now, let’s try to understand how fluent validations can be used to validate the properties of type collections.

Collections can be of two kinds:

  • Collection of basic data type (int, string, bool, etc.)
  • Collection of custom types

Let’s see how these can be validated.

Collections of Basic Data Type

In the first article of this series, we have created a type, Student and we also created a validator for this type. This type has a simple collection property – Courses. This property is basically a list of strings. We already have seen how to validate such collection.

We can use RuleForEach method to run validation rules against every entry in the collection. Then we can use multiple built in validators (or custom validators ) to apply validation rules. Also, in case we want to display the index at which the validation error has occurred, we can use the placeholder {CollectionIndex}.

The code snippet given below shows the usage of RuleForEach method and {CollectionIndex} placeholder.

Collections of Custom Data Types

Now, let’s have a look at how to validate collections of custom data types. Let’s create a custom type Course, which has two properties, Id and Name. Then let’s create simple validator for this type.

The code snippet given below shows three types:

  • The Course class
  • Student class, which now uses collection of Course instead of collection of strings
  • CourseValidator class which has basic validation rules specified for validating the Course type

Then the StudentValidator can use RuleForEach and then SetValidator methods on to set CourseValidator for each entry in Courses Collection

Alternatively, instead of SetValidator method call, we can use ChildRules method to specify the validation rules for the child collection. The code snippet from StudentValidator.cs, which uses ChildRules method to specify the validation rules.

My opinion is – it is better to use SetValidator method because then the validation rules can be easily reused anywhere else.

That’s it for this article ! I hope you find this information helpful. Let me know your thoughts.

Leave a ReplyCancel reply