Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

How to Display Validation or Error Messages in Angular Forms

This guide covers how to display validation or error messages with Angular forms. It looks at both template-driven forms and reactive forms.

Sep 24, 2020 • 6 Minute Read

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.

      npm install -g @angular/cli
    

Then type below command to create a new Angular project.

      ng new ngValidation
    

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

      cd my-app
ng serve --open
    

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.

      // app.module.ts

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

imports: [
    BrowserModule, ReactiveFormsModule
  ],
    

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

      <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>
    

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

      // 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 ]
    });
  }
}
    

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.

      // 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 ]
    });
  }
}
    

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

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

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

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

      // app.component.ts

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

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

      <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>
    

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.

Learn More

Explore these Angular courses from Pluralsight to continue learning: