Advanced Validation with Angular Reactive Forms

Out of the box Angular provides a minimal set of validators but in the real world you need many many more. Validation is really important to give the user feedback which will improve the experience and prevent issues down the road.

Backend APIs usually have extensive validation going on and we are left trying to recreate it on our side. I’m going to show you how you can take a popular backend validation library and use it on the client side to create a 1 to 1 validation match saving everyone time!

First, lets install Joi which is a popular backend object schema validator. Its kinda big and optimized for the backend but luckily for us there is a browser version that lets us slim down some of the depedencies:

npm i joi-browser --s

Next lets create a wrapper that will map Joi errors to an Angular format:

This accepts a NgControl from our Reactive forms and a Joi Schema. We can hook this up in our forms really easily like:

And thats it! We can do better though, typically these validators are shared amongst controls so why not group them together? Also, using decorators we can clean up this syntax:

then our form hookup can look like this:

To pull this off, we just need to create a decorator wrapper for our joiValidators.

And thats it! Pretty sweet huh?!

I’m #ngPanda

I hope you enjoyed the post, if you liked it follow me on Twitter and Github for more JavaScript tips/opinions/projects/articles/etc!

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.