DEV Community

Cover image for Simplify validation error handling in Angular with `ng-input-validation`

Simplify validation error handling in Angular with `ng-input-validation`

πŸ’¬ Introduction

In Angular, displaying validation errors in a form can quickly become repetitive and verbose. It is to simplify this part that I have developed a small library: ng-input-validation, which centralizes and automates the display of error messages in an elegant and reusable way.

In this post, I show you how I used to do it and how I do it today πŸ‘‡


❌ Before: a repetitive management in each field

Before, for each form field, it was necessary to write several conditions to display the error messages:

πŸ‘‰ Result: a lot of repetitive code to maintain, especially when you have multiple fields.

βœ… Now: a single line thanks to ng-input-validation

With ng-input-validation, everything is managed automatically from the FormControl.
Here is what the same field looks like today:

And your FormGroup :

Where before it was necessary to write several @if, today a single line is enough. The component automatically displays the correct error message according to the type of validation (required, email, minLength, etc.).


βš™οΈ Bonus:

You can also manage backend errors or add custom messages for each type of error.


πŸ“¦ Installation

npm i ng-input-validation
Enter fullscreen mode Exit fullscreen mode

And don’t forget to import it into the Angular component.


πŸ’‘ Conclusion

This library allowed me to:

  • Save time on form management;
  • Keep a cleaner and maintainable code;
  • Standardize error messages in all my Angular applications.

πŸ‘‰ The project is open-source on npm:
πŸ”— https://www.npmjs.com/package/ng-input-validation

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.