Show Validation Error Messages for Reactive Forms in Angular 9
Home
About
Articles
In Angular there are two different types of forms for a user to input data: reactive and template-driven . I personally prefer using reactive forms as they seem to follow the separation of concerns principle, where the core functionality is in the component and the presentation layer is stored in the template.
We can define a reactive form within a component and check if the form is valid, but if there’s an error, how do we indicate this to the user in a manner they can understand and rectify accordingly?
In this example, I’ll define a reactive form with one text field. We’ll configure this field to have a few validation rules before the user can submit the form. These will be to set the field as required , it’s value to be of a minimum character length of 3 and have a maximum character length of 30.
The reactive form defined in the component:
Using data binding in Angular, we can dynamically change the label to indicate the field is required. This will at least let the user know that the field is not optional:
We can also use data binding to apply the classes ‘valid’ or ‘invalid’ to the field to indicate if there is a validation error (or if the field is valid) :
We’ll need to clearly indicate to the user if a field is required, or if the user has not met the validation rules set for a minimum character length or exceeded a maximum character length. You could also add to this to include other validation rules such as email addresses or forbidden names. Let’s show each error message using data binding and HTML:
Required error message:
Minimum length error message:
Maximum length error message:
Finally, we can disable the submit button if the form is invalid:
Instead of duplicating this code for each field and for all forms, a better approach might be to abstract this into a separate component that can be reused across the codebase. However, this should hopefully be a good example of how to show validation error messages to the user in a reactive form.
There are often scenarios in Angular where we need to communicate between components, specifically to send data from a child component to it’s parent component. Consider this Angular 12 app for managing a to do list: Read more
If you’re interested in building a caching service for Angular that will store the observable for a HTTP call in cache, there is an excellent article by Yury Katkov that will explain exactly how to do this using RxJS. Read more
Have you ever looked for a piece of HTML in the code of an Angular app and found something similar to <ng-container *ngTemplateOutlet=”navBarTemplate”></ng-container> instead? Read more
RSS