DEV Community

Cover image for Excuse Me, Could You Validate this for me, Please?
enterprise2062 for DealerOn Dev

Posted on

Excuse Me, Could You Validate this for me, Please?

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.

Cover photo by Chrissy Jarvis via Unsplash

City skyline across a river

Photo by Hermes Rivera via Unsplash

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 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 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.

    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:

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

Photo by David Beale via Unsplash

Discussion (1)

Collapse
tyrrrz profile image
Oleksii Holub

FluentValidation is great if all properties on an object are validated independently. If your rules are cross-dependent it gets much harder using FluentValidation to the point that some complex rules become almost impossible.