Simple validation with validators

There are many ways to perform a validation of our models living within the system.
Whether there’s an incoming request from the user who would like to create an account or there’s a need to ensure about the correct amount of money in a bank transaction, the validation process should always (I really mean that) take place. In today’s post, I’d like to present one of the possible solutions that might help you validate your entities.


 

Let’s start with a definition of the IValidator interface:

If the validation fails, there will be a ModelValidationException thrown:

If you’re not a fan of throwing the exceptions in such cases, you might as well return a boolean or IEnumerable in order to check whether there are no error messages – it’s totally up to you, as the outcome shall remain the same.

Now, let’s assume there’s the following class (that would be a ValueObject in the world of DDD):

And we could define the following profile validator:

Once it’s completed, you can easily use these validators e.g. within your business logic services. It also comes in handy to configure them within the IoC container. For example using it with the Autofac could look like this:

And that would be all, it’s a relatively easy concept, yet also quite useful, mostly due to the fact that having a set of interfaces for validation purposes makes it easier for testing the code.

8 Comments Simple validation with validators

  1. Pingback: Dew Drop - August 8, 2016 (#2304) - Morning Dew

    1. Piotr Gankiewicz

      Hi,
      Yes, it’s a very good library, but in case someone would prefer to have his own solution due to some specific reasons it can be achieved using a quite simple interface mentioned above :).

      Reply
  2. zomat

    It looks like a nice solution. But where can I use the validation. In userService?

    Reply
    1. Piotr Gankiewicz

      Either in UserService or even separately, for example, let’s say that you would like to have a sophisticated flow of registering a new user account. At first, you could perform the validation, then create an account and eventually send him an email message. All of that business logic may be contain withing different unit such as CommandHandler or so.

      Reply
      1. Zomat

        Make sense. But I could not imageine to separate validation logic. Message send operation may be in command handler, But how can I seperate the validation?

        Reply
  3. Gerard

    Hello PIOTR GANKIEWICZ, thank you very much. Can you put or follow one simple code example where your validation is used?

    Reply

Leave A Comment

Your email address will not be published. Required fields are marked *