Error Pipes for Angular Form Validation

Chris House
SlackerNoon
Published in
3 min readAug 7, 2019

In part two of my Angular Form Series, I am going to introduce a pipe to translate error codes into strings which will reduce the amount of html needed to display the errors.

In my previous article I explain how to use Async form validators for custom validation at run time.

Again we will start with a login form:

The goal here is to replace inline html error messages with a pipe.

Here we have two different error messages that will show if the field is invalid, and a different div will show if the username exists already.

My goal is to reduce the custom html error messages, and have one div to handle all messages.

The final html code is above. It says, if there are errors on this field, no matter the amount of errors, send them through the inputError pipe.

The pipe is quite simple in this example, and will transform the error code into a human readable string. One reason to do this is if we want to translate error messages to different languages through a language translation service. (you can also use a language translation pipe). Below we use a translation directive that receives a error code, and then it translates to whatever language we need.

In a real world application you will have more codes like required field, min length, max length, numbers greater than zero, etc… You will also have custom error sentences you may want to use this for, for business rules.

Full Stackblitz example

Part three: In my next article, I explain how to translate those error messages into French, and back to English!

--

--