How to validate Angular template-driven forms

Angular is an open-source JavaScript framework primarily used to develop single-page applications. It is a component-based framework that allows us to divide our application's functionalities into small, independent, and reusable components.

Angular forms

Angular provides extensive support for integrating forms in our application. There are two forms that Angular supports, template-driven and reactive forms. Angular provides the feature of form validations, form controls, form submission, and handling user inputs. In this Answer, we will explore the implementation of validations and error messages in template-driven Angular forms to enhance user experience and data integrity.

Validations in template-driven forms

Template-driven forms are useful when creating simple forms. It allows handling the form structure and validations in the templatethe .html file itself, which makes it easier to create interactive forms with less code. Template-driven forms use directives like ngModel, ngForm, ngSubmit, and ngModelGroup to handle form controls, data binding, and form submission. To get a hands-on idea of implementing validations in template-driven forms, let us create a simple form.

Coding example

We create the form in the code widget below. The form uses Bootstrap, which we include in the app-component.css file:

<form>
  <div class="form-group">
    <label for="exampleInputEmail1">Email address</label>
    <input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email">
    <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
  </div>
  <div class="form-group">
    <label for="exampleInputPassword1">Password</label>
    <input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
  </div>
  <div class="form-check">
    <input type="checkbox" class="form-check-input" id="exampleCheck1">
    <label class="form-check-label" for="exampleCheck1">Check me out</label>
  </div>
  <button type="submit" class="btn btn-primary" style="margin-left:45 %">Submit</button>
</form>
Code of form without validations

Let's see the code explanation below:

  • Line 1: We create the form using the form tag.

  • Line 4: We create an input field of type email to get an email from the user.

  • Line 9: We create an input field with type password to get the password from the user.

  • Line 15: We create a button to submit the form.

Importing FormsModule

To create a template-driven form, we need to import FormsModule from the @angular/forms in the app.module.ts file. The code for app.module.ts file is given below:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { FormsModule } from '@angular/forms';

@NgModule({
  imports: [
    BrowserModule,
    FormsModule
  ],
  declarations: [
    AppComponent,
  ],
  providers: [],
  bootstrap: [ AppComponent ]
})
export class AppModule { }
Code to import FormsModule
  • Line 4: We import FormsModule from @angular/forms.

  • Line 9: We include the FormsModule in the imports array to use the functionalities of the module in the application.

Now we will dive into the actual implementation of defining our form validation rules in the template.

Implementing validations

For that, let's explore the updated code implementation of app.component.html file below:

<div class="container">
  <div >
    <form #templatedrivenForm="ngForm">
      <div class="form-group">
<!-- Email input area -->
        <label for="name">Email</label>
        <input type="text" class="form-control" id="name" required name="email" pattern="[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}" [ngModel]="formEmail" #email="ngModel">
<!-- Invalid Email messages  -->
        <div *ngIf="email.invalid && (email.dirty || email.touched)" class="alert alert-danger">
          <div *ngIf="email.errors?.['required']">
            Email is required.
          </div>
          <div *ngIf="email.errors?.['pattern']">
            Invalid email format
          </div>
        </div>
      </div>
      <!-- Password input area -->
      <div class="form-group">
        <label for="exampleInputPassword1">Password</label>
        <input [ngModel]="formPassword" #password = "ngModel" name="password" type="password" class="form-control" id="exampleInputPassword1" placeholder="Password" required minlength="8">
      </div>
    
      <!-- Error messages for invalid passwords -->
      <div *ngIf="password.invalid && (password.dirty || password.touched)" class="alert alert-danger">
    
        <div *ngIf="password.errors?.['required']">
          Password is required.
        </div>
        <div *ngIf="password.errors?.['minlength']">
          Password should contain atleast 8 characters
        </div>
    
      </div>
      <button type="submit" class="btn btn-success" [disabled]="!templatedrivenForm.form.valid">Submit</button>
    </form>
  </div>
</div>
Code to implement validations and error messages in a template-driven Angular form

Let us see the code explanation below:

  • Line 3: We create the template reference variable, templatedriveForm. This variable helps in accessing control of the form and its input fields.

  • Line 7: We give the name attribute a value of email. We bind the name attribute with the ngModel directive by #email="ngModel". The validations defined for the input field are required and pattern. The required attribute tells that the input field cannot be empty. The pattern attribute takes a regular expression of the email format.

Note:An important point to remember is to include the [ngModel] directive in the input field by binding it to a variable defined in the app.component.ts file as shown by [ngModel]="formEmail". This helps in two-way data communication from the app.component.ts file.

  • Lines 9–15: We define the error messages that display if the email is not valid.

    • Line 9: We define a div with the ngIf directive that checks if email rules are invalid, and the email is dirty or touched.

Note: email.dirty is true if the input value has changed, whereas email.touched is true when the user interacts with the input field.

  • Line 10: If the condition in line 9 is true, we check if no value exists in the email form control and display the error message Email is required on the screen.

  • Line 13: Similarly, if the condition at line 9 is true, then we check if the existing value in the email form control does not follow the email format as described in the pattern attribute and display Invalid email format on the form.

  • Line 21: We give the name attribute a value of password. We bind the name attribute with the ngModel directive by #password="ngModel". The validations defined for the input field are required and minlength. The required attribute tells that the input field cannot be empty. The minlength attribute tells the least number of characters that should be included in the input field.

  • Lines 25–34: We define the error messages that will display if the password form control is invalid.

    • Line 25: We define a div with the ngIf directive that checks if the password rules are invalid, and the password is dirty or touched.

    • Line 27: If the condition in line 25 is true, then we check if no value exists in the password form control and display the error message Password is required on the screen.

    • Line 30: Similarly, if the condition in line 25 is true, we check if the password form control's value contains less than 8 characters and display Password should contain atleast 8 characters on the form.

In this way, we can display error messages on template-driven angular forms. The complete code for the form is shown below.

Complete coding example

To see the code in action, please click the "Run" button

@import url('https://unpkg.com/bootstrap@3.3.7/dist/css/bootstrap.min.css');
Complete code for template-drive form

By adhering to the guidelines above, we can easily integrate validations in our forms and display error messages to our users.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved