Author avatar

Chris Parker

How to Display Validation or Error Messages in Angular Forms

Chris Parker

  • Sep 24, 2020
  • 6 Min read
  • 197 Views
  • Sep 24, 2020
  • 6 Min read
  • 197 Views
Languages Frameworks and Tools
Front End Web Developer
Client-side Frameworks
Angular

Introduction

Angular is making it easier to build apps for the web. Angular combines dependency injection and declarative templates, and it has integrated best practices to solve development problems.

Forms are one of the most common features in any app. Users can use forms to log in, book a flight, or order food. You can enhance the overall data quality by validating user input for accuracy.

This guide will cover how to display validation or error messages with Angular forms.

Create a New Angular Project

Install Angular globally by using the following command.

1
npm install -g @angular/cli
javascript

Then type below command to create a new Angular project.

1
ng new ngValidation
javascript

Add a few files and install some dependencies. Navigate to the root app directory and type the following command to start the server.

1
2
cd my-app
ng serve --open
javascript

You'll create a form with a single input to get an understanding of Angular forms. First, you must include reactive forms in app.module.ts.

1
2
3
4
5
6
7
// app.module.ts

import { ReactiveFormsModule } from '@angular/forms';

imports: [
    BrowserModule, ReactiveFormsModule
  ],
javascript

Now, we can add the below code to display the form.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<div style="text-align:left">
  <h1>
    Welcome to {{title}}!!
  </h1>
  <form [formGroup]="myForm" novalidate>
        <div class="form-group">
          <label class="center-block">Username:
            <input class="form-control" formControlName="username">
          </label>
        </div>
        <div *ngIf="myForm.controls['username'].invalid && (myForm.controls['username'].dirty || myForm.controls['username'].touched)" class="alert">
            <div *ngIf="myForm.controls['username'].errors.required">
            Please enter username
          </div>
        </div>
  </form>
<p>myForm value: {{ myForm.value | json }}</p>
<p>myForm status: {{ myForm.status | json }}</p>
</div>
javascript

You also need to update the app.component.ts file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// app.component.ts

import { Component } from '@angular/core';
import { FormGroup,  FormBuilder,  Validators } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'My Angular Form Validation Example';
   myForm: FormGroup;
   constructor(private fb: FormBuilder) {
    this.createForm();
  }
   createForm() {
    this.myForm = this.fb.group({
       username: ['', Validators.required ]
    });
  }
}
javascript

Template-Driven Forms

You can create a template-driven form in Angular template syntax using the form directives. Build template-driven forms by following these steps:

  1. Create a new Angular component with an initial form layout.

  2. Add data properties to bind for each form control and add an attribute to each form-input control.

  3. Show/hide validation messages.

  4. Handle form submit using ngSubmit.

  5. Optional: Add feature to disable the submit button initially and enable only after the form is valid.

Reactive Forms

Reactive forms are used to create forms that contain a reactive style. A reactive style of programming is enabled by Angular reactive forms that supports detailed management of the data flowing between a non-UI data model (typically retrieved from a server) and a UI-oriented form model that contains the states and values of the HTML controls on the screen. Reactive forms provide the comfort of utilizing reactive patterns, testing, and validation.

Let's look at an example.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// app.component.ts

import { Component } from '@angular/core';
import { FormGroup,  FormBuilder,  Validators } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Angular Form Validation Tutorial';
   myForm: FormGroup;
   constructor(private fb: FormBuilder) {
    this.createForm();
  }
   createForm() {
    this.myForm = this.fb.group({
       username: ['', Validators.required ]
    });
  }
}
javascript

Here, you need to import a few modules from @angular/forms.

  1. FormGroup
  2. FormBuilder
  3. Validators and ReactiveFormsModule
1
2
3
4
5
// app.component.ts

constructor(private fb: FormBuilder) {
    this.createForm();
}
javascript

Use a FormBuilder to handle validations. Create a form with all the validation rules inside the constructor.

1
2
3
4
5
6
7
// app.component.ts

createForm() {
  this.myForm = this.fb.group({
       username: ['', Validators.required ]
  });
}
javascript

Assign the validation rules to the form object in this code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<form [formGroup]="myForm" novalidate>
        <div class="form-group">
          <label class="center-block">Username:
            <input class="form-control" formControlName="username">
          </label>
        </div>
        <div *ngIf="myForm.controls['username'].invalid && (myForm.controls['username'].dirty || myForm.controls['username'].touched)" class="alert">
            <div *ngIf="myForm.controls['username'].errors.required">
            Please enter username
          </div>
        </div>
  </form>
<p>Form value: {{ myForm.value | json }}</p>
<p>Form status: {{ myForm.status | json }}</p>
javascript

Conclusion

You have now seen both template-driven forms and reactive forms. When a user touches any input field but does not enter a value, an error message will be shown. Again, when the user blurs the input field without entering a value, an error message will be displayed. Thus, we are able to display validation messages for the form fields.

1