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 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>
Let's see the code explanation below:
Line 1: We create the form using the
formtag.Line 4: We create an
inputfield oftypeemailto get an email from the user.Line 9: We create an
inputfield withtypepasswordto 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 { }Line 4: We import
FormsModulefrom@angular/forms.Line 9: We include the
FormsModulein theimportsarray 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>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
nameattribute a value ofemail. We bind thenameattribute with thengModeldirective by#email="ngModel". The validations defined for the input field arerequiredandpattern. Therequiredattribute tells that the input field cannot be empty. Thepatternattribute 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 theapp.component.tsfile as shown by[ngModel]="formEmail". This helps in two-way data communication from theapp.component.tsfile.
Lines 9–15: We define the error messages that display if the
emailis not valid.Line 9: We define a
divwith thengIfdirective that checks ifemailrules are invalid, and theemailis dirty or touched.
Note:
email.dirtyis true if the input value has changed, whereasemail.touchedis 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
emailform control and display the error messageEmail is requiredon the screen.Line 13: Similarly, if the condition at line 9 is true, then we check if the existing value in the
emailform control does not follow the email format as described in thepatternattribute and displayInvalid email formaton the form.Line 21: We give the
nameattribute a value ofpassword. We bind thenameattribute with thengModeldirective by#password="ngModel". The validations defined for the input field arerequiredandminlength. Therequiredattribute tells that the input field cannot be empty. Theminlengthattribute 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
passwordform control is invalid.Line 25: We define a div with the
ngIfdirective that checks if thepasswordrules are invalid, and thepasswordis dirty or touched.Line 27: If the condition in line 25 is true, then we check if no value exists in the
passwordform control and display the error messagePassword is requiredon the screen.Line 30: Similarly, if the condition in line 25 is true, we check if the
passwordform control's value contains less than 8 characters and displayPassword should contain atleast 8 characterson 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');
By adhering to the guidelines above, we can easily integrate validations in our forms and display error messages to our users.
Free Resources