.NET Backend

Valit – dead simple, fluent validation for .NET Core

About two months ago I worked on the microservice for my company’s new product. The whole thing was based on the CQRS pattern which is basically about splitting the application into reads (queries) and writes (commands). I came to the point when I wanted to validate a command object received from RabbitMQ. Without thinking, I started coding another if statements which after a while became my „domain logic”. I’m not going to present the example code because I’m sure that majority of you have seen this at least once in your life. Back to the story, when I finished the implementation and looked at the creature I created, I was like „Well, that sucks”. I simply didn’t like that not only because the code itself was long and quite complicated. It was simply very hard to read and understand. A few minutes later my friend Daniel visited me and asked about my progress. I shared my opinions about the code and I proposed him to create a simple library which could help other .NET developers with validation. That’s how my first (finished) open source project was born. We called it Valit.

 

What is Valit?

Valit is dead simple validation for .NET Core. We decided to create fluent API which would allow you to create nice and very readable validators. Did we succeed? Well, I leave it up to you 馃槈 Let’s move to the code and see how it works.

In order to create a validator, you need to go through few steps. It’s worth mentioning that not all of them are mandatory. The steps are:

  • Creating a new instance of validator using Create() static method.
  • Choosing validation strategy using WithStrategy() method (not required).
  • Selecting property using Ensure() method and defining rules for it.
  • Extending rules with custom errors (such as messages or error codes), tags and conditions. (not required).
  • Applying created rules to an object using For() method.

Having the validator created, simply invoke Validate() method which will produce the result with all the data.

Let’s try it out with a very practical example. Imagine that you’re task is to validate model sent from registration page of your app. The example object might look as follows:

 


    public class RegisterModel
    {
        public string Email { get; set; }        
        public string Password { get; set; }
        public ushort Age { get; set ;}
    }

 

These are the validation criteria:

  • Email is required and needs to be a proper email address
  • Password is required and needs to be at least 10 characters long
  • Age must be greater than 16

This is how you can handle such scenario using Valit:

 


    void ValidateModel(RegisterModel model)
    {
        var result = ValitRules<RegisterModel>
            .Create()
            .Ensure(m => m.Email, _=>_
                .Required()
                .Email())
            .Ensure(m => m.Password, _=>_ 
                .Required()
                .MinLength(10))
            .Ensure(m => m.Age, _=>_
                .IsGreaterThan(16))
            .For(model)
            .Validate();

        if(result.Succeeded)
        {
            // do something on success
        }
        else 
        {
            // do something on failure
        }
    }

 

Pretty cool, right? Of course, the above example was fairly simple but don’t even think it shows all capabilities of this library. If you want more, go check the documentation.

 

But there is Fluent Validation already existing…

There’s one more part of the story from the first paragraph I haven’t told you yet. The day after Daniel and I started work on the project, I decided to show it to my colleagues. One of them asked me „Well, why didn’t you use Fluent Validation instead?”. My face was like:

 

 

Actually, the answer is pretty simple. I didn’t know that. So, I visited the repository on GitHub and saw these numbers:

  • 2,689 stars
  • 1,120 commits
  • logo added 8 years ago

Honestly, I thought it was over. How could we compare to a library which is so popular and has been developing for 8 years? But when I thought about it, actually there were quite a lot benefits of still doing that:

  • I would do serious open source project after work
  • I would learn to create libraries for other developers
  • I would learn to manage open source projects
  • I would learn more DevOps

And you know what? After two months of work, it’s safe to say I really learned a lot. I stopped doing my „top secret” projects that probably would never have been released, and I started doing open source:

 

 

I learned how to (re)design an API for my library, which explains why currently Valit’s repo contains over 200 commits. I learned how to manage the repository and plan work for sprints:

 

 

I also learned a lot about DevOps as well which result in two blog posts:

Everything thanks to the simple library I created two months ago. So, even if folks will not like it, I still win!

 

Want to contribute?

The source code is available on GitHub and I encourage you to check it out. If you’d like to help us, feel free to grab any task from the issues or create one if you have any ideas or you spotted a bug. There’s also a contribute guideline which should help you start working with the code. By the way, I’d like to thank Pawe艂 Skaruz who has already created very first Pull Request to Valit and added support for Guid type. Thanks a lot once again!

So, that’s it. Please let me know down in the comments what are your thought about Valit. And if you like it,聽please leave a star on GitHub 馃檪


LINKS ONCE AGAIN: