Fluent Validation: Passing Custom Error Code Along with Validation Messages

Fluent Validation is one of the most popular validation frameworks that enables developers to apply code validation rules in a fluent manner with support of standard models. In contrast to many modern validation approaches where the rules are declaratively mixed up with the models themselves using attributes (or annotations), Fluent Validation very firmly separates the models from the rules and has you define Validator classes instead. We had chosen Fluent Validation on a recent project because of its flexibility and ability to cover such a wide variety of use cases such that it validates anything in any context.

A recent new feature added to Fluent Validator.

Up till now in case of any validation failure, Fluent Validator was capable to pass just the error message to all the subscribed client applications. However there are many cases where it is required to pass the Error code also along with the validation messages, like when we are validating the objects for services and service consumer may require to apply its own message based on received error code. Although, with the previous version of Fluent Validator, there were few workarounds to achieve the same but they were inefficient and complicated. One of the workaround was that we pass the error code in the placeholder meant for error message but it failed when we had to pass both message and error code together.

Considering the above said requirement, now Fluent Validator comes with a new place holder called ErrorCode to persist the error code in parallel to the ErrorMessage variable.

So now suppose Client A requires just Error Message then pass only Error Message by calling WithMessage(…) function.

Screenshot 2016-01-13 22.29.26

Now suppose a scenario where we have a client which need only Error Message or Error Code and other clients which need both code & message then call both WithErrorCode(…) & WithMessage(…) in a chain as described in image below.

Screenshot 2016-01-13 22.29.39

Let’s Code Now 🙂

So now the more important stuff, i.e. code to apply the new feature in action. According to Fluent Validator framework, we create the validator class name with following naming convention <ClassName>Validator,  for example for Customer Class validator class name would be CustomerValidator.

Below is the simple example code to validate customer model.

using FluentValidation;

public class CustomerValidator: AbstractValidator<Customer> {
public CustomerValidator() {
RuleFor(customer => customer.Surname).WithErrorCode("ERR-112");

   RuleFor(customer => customer.Forename).NotEmpty().WithMessage("Please specify a first name");
RuleFor(customer => customer.Discount).NotEqual(0).When(customer => customer.HasDiscount);
RuleFor(customer => customer.Address).Length(20, 250).WithErrorCode("ERR-154").WithMessage("Address cannot be empty");
RuleFor(customer => customer.Postcode).Must(BeAValidPostcode).WithMessage("Please specify a valid postcode");
}

Once the validation class is created, We can either pass just error code/error message to the client OR pass both error code & message in chaining. Following code snippets describes the same in detail.

  1. Passing either of ErrorCode or ErrorMessage
RuleFor(customer => customer.Surname).NotNull().WithErrorCode("ERR-112");

Or

RuleFor(customer => customer.Surname).NotNull().WithMessage("Invalid Length");

Now in the below code snippet when we apply the validation check on the Customer Object, we get ValidationResult Object as output and from this object we can get either of Error Code or Error Message, based on what all data we have passed.

Customer customer = new Customer();
CustomerValidator validator = new CustomerValidator();
ValidationResult results = validator.Validate(customer);

bool validationSucceeded = results.IsValid;
IList<ValidationFailure> failures = results.Errors;
  1. Passing both ErrorCode and ErrorMessage in chaining.
RuleFor(customer => customer.Surname).NotNull().WithErrorCode("ERR-112").WithMessage("Surname cannot be empty");

In below code snippet since we are passing both ErrorMessage & ErrorCode in chaining we would get both ErrorCode & Message as part of ValidationResult object.

Customer customer = new Customer();
CustomerValidator validator = new CustomerValidator();
ValidationResult results = validator.Validate(customer);

bool validationSucceeded = results.IsValid;
IList<ValidationFailure> failures = results.Errors;

The below image shows the Error code and Error Message captured in ValidationResult Object.

Screenshot 2016-01-13 22.30.02

Conclusion:

This new feature is incorporated with FluentValidator in its latest version and can be picked from following GITHUB location:

https://github.com/JeremySkinner/FluentValidation

Vikas Hajela

Vikas Hajela

Technical Manager

Vikas Hajela is a Technical Manager for 3Pillar Global and has 14+ years of experience in the IT Services industry. He has been involved in the delivery of IT Strategies, Solution Architectures, Mission Critical and High-Visibility Applications, Enterprise SOA and Integrations, and Application Security Implementations, among others. He has also consulted customers on Application Security, Portals, Content Management, and Cloud Integration. Vikas has a passion for identifying the needs of the Enterprise in context of the larger strategy and ecosystem, and spearheading solutions that are holistic and leverage a broad multidisciplinary approach. He delights in designing solutions that balance the tactical needs of the project with the long term benefits to the enterprise.

2 Responses to “Fluent Validation: Passing Custom Error Code Along with Validation Messages”
  1. Shilpi on

    Very helpful.

    Reply
  2. Smithc861 on

    Howdy! I basically would like to give a huge thumbs up for the good data you’ve got here on this post. I will probably be coming once again to your weblog for far more soon. faccgdbddadgddea

    Reply
Leave a Reply

Related Posts

3 Topics We Should Be Talking About at BrainstormTech Our 3Pillar clients, regardless of industry, share one common trait - they need help strategizing, designing, and delivering revenue-generating digita...
4 Reasons Everyone is Wrong About Blockchain: Your Guide to ... You know a technology has officially jumped the shark when iced tea companies decide they want in on the action. In case you missed that one, Long Isl...
3 Cloud Optimization Projects That Will Pay for Themselves i... AWS introduced 1,430 new features and tools in 2017, including 497 in the 4th quarter alone. This means that it can be a challenge for even the mos...
The Connection Between Innovation & Story On this episode of The Innovation Engine, we'll be looking at the connection between story and innovation. Among the topics we'll cover are why story ...
Go Native (App) or Go Home, and Other Key Takeaways from App... I just returned from my first WWDC. I feel like I learned more in a week at Apple’s annual developer’s conference than I have in years of actually dev...