Excuse Me, Could You Validate this for me, Please?
Tags: csharp, validation, library, dotnet
Published: 2019-09-27 16:12:47

While Grand Rapids (Michigan, not Minnesota) is not generally considered a big city there is one building, nestled along the banks of the Grand River, extremely blue with its own parking ramp on the bottom requiring ticket validation to exit.  Validation is the only way to avoid paying the outrageous price for parking while in there talking to IT recruiters.  

<figcaption>Cover photo by <a href="https://unsplash.com/@crissyjarvis">Chrissy Jarvis</a> via Unsplash</figcaption>

![City skyline across a river](https://thepracticaldev.s3.amazonaws.com/i/s30vlq1xicilkgm7g3s2.jpg)
<figcaption>Photo by <a href="https://unsplash.com/@hermez777">Hermes Rivera</a> via Unsplash</figcaption>

If you are spending your time talking to recruiters then money is probably tight and that makes validation a very useful tool. Inside the recruiter’s office, the lady in charge of the validation stamp sits behind a pair of sliding glass windows much like a doctor’s office setup.  She only reluctantly slides open a window to talk to you or pass you forms, and informs all the supplicants that the validation can only be signed off on once you meet with the recruiter.

_Like we got all dressed up in a suit and traipsed our way here to get a free chance to buy popcorn at the lobby gift shop?_  The validation process is a **gatekeeper situation**, if you don’t measure up, you are going to pay the price, so fill out this form, go sit down and be quiet.

---

How about once you have a job and have software to make run, and furthermore keep running?  Once again validation can come in handy by checking to make sure the latest batch of data doesn’t blow up the finely tuned system you know and love. Say, how about if you get one of those gatekeeper types who slam the door in the face of data that doesn’t behave?  

Now you may want to protest and say these things have nothing in common, but they probably should, especially if you are the self-validator type of programmer.  Instead of writing all the tests necessary at the time you are solving the problems of your application, why not bring in a pro to help you make the runtime tests needed to keep things running smoothly? 

.NET provides some pretty nifty built in tools called [Data Annotations](https://docs.microsoft.com/en-us/dotnet/api/system.componentmodel.dataannotations?view=netframework-4.8) that allow you to decorate your data class with requirements and checks.  However the process tends to create a confusing scenario where locating the particular validations can be tricky and they bloat your otherwise clean data models with extra verbiage. 
 
[FluentValidation](https://fluentvalidation.net/) brings us a nicely decoupled model for adding validation to our existing classes by simply allowing us to create a separate class where we can add or subtract our validation features with very little damage to our original class.  It is easy to install FluentValidation via nuget console application so that we can begin to use this open source help.  Watching the install you may notice that it is plugging in a number of connections to the `System.ComponentModel.Annotations` Libraries. Hey, this is leveraging the same tools!

The architecture of FluentValidation purports to be for use with Core components however it can be used with .Net 4.5.2 components as well.  

The basic model for using the FluentValidation tools is to create a `Validation` Type class that inherits through an abstract method.

```csharp
    public class TaskValidator :AbstractValidator<TaskTrackingBase>
```

Then you move on simply by putting in your validators in the constructor.  The common models for demonstration are `.NotNull()` and `.NotEqual()`. There are currently 22 built in validators with interesting things such as regular expressions and email validation types. You can also write custom validators if none of the current tools fit your needs.

The process of check validation is:
```csharp
Customer customer = new Customer(); 
CustomerValidator validator = new CustomerValidator(); 
ValidationResult results = validator.Validate(customer); 

if (! results.IsValid) { foreach(var failure in results.Errors) 
{ 
  Console.WriteLine("Property " + failure.PropertyName + " failed validation. 
Error      was: " + failure.ErrorMessage); 
} 
```
The object will create a list of errors that you can scan and handle as you find helpful.

There is an advertised feature where you are supposed to be able to use `{CollectionIndex}` in order to get the location of the item in a group of objects that raised the error(s). On my version (8.4) and it appears that  this doesn’t work.  However, the list under the `PropertyName` does include an index to help you locate the position of the problem.  So much nicer than dealing with the SQL error that vaguely states that some item has a problem.  Good luck with that, BTW!

The impact on your original class can be minimized or could reveal some less than awesome coding that would benefit from some rewriting anyway. Once you are used to working with the product FluentValidation is a nice tool to gain added benefits without a lot of extra coding.

Overall the tool set seems to be a well-executed library that can make it clean and fairly easy to set up gatekeepers on your data with organized validators. It can help you to avoid paying a high price searching through mystery errors and errant data by planning ahead and intercepting them before they cause a problem.

![Old Michigan license plate](https://thepracticaldev.s3.amazonaws.com/i/7fhmamo90j31oblrwrpo.jpg)
<figcaption>Photo by <a href="https://unsplash.com/@davidbeale">David Beale</a> via Unsplash</figcaption>