In this article, I will explain about validating user inputs using Angular forms. Generally speaking, , forms are used to handle user’s input! With the help of forms, we can do CRUD operations such as create, read, update, delete. Basically, speaking of forms in Angular, Angular forms are classified into two types, such as Reactive forms and Template-driven method. Both types of forms are being used to collect input from the user. Before getting started with form validation we can take an overview of both Reactive and Template-driven method.
Reactive Forms
The reactive forms are also called Model-driven forms, the reactive forms provide an approach for UI to handle the input towards the component variable. It can be used with complex forms with a greater number of form fields but it requires multiple complex validations in which custom validations are involved in it. The reactive forms require the JSON structure to be sent with values in the form.
Template Driven Method
The template-driven method is very useful in using simple forms like login forms, the template-driven method uses two-way data binding, so with the help of two-way data binding, we can assign a value to a variable from the UI. This type of form is used in very basic forms and requires simple logic.
Difference between Reactive and Template-driven method
Reactive Forms |
Template-Driven Method |
Reactive forms are created in the component class. |
Template-driven forms are created by using directives. |
Reactive forms are structured by the data model. |
The template-driven method is unstructured in the data model. |
The predictability is synchronous in reactive forms. |
The predictability is asynchronous in template driven. |
The level of scalability in reactive form has low-level API access |
The level of scalability in the template-driven method has the abstraction of the top API’s |
Form validation is done by using functions |
Form validation is done by using directives |
So, in this article, we will be seeing about designing a form and performing form validation using the template-driven method, in addition to that I have uploaded source code containing some additional files such as config.JSON, EmployeeService.ts service file and as well as a model class file named as employee.ts. This article's source code will be continued in the
next article, where we will see about pushing input values from a form to a list. Now in this article, we are about to use third-party libraries like bootstrap and you can find more information about bootstrap from the following
link; also the main point is we can track the control state and validity with the model.
By using ngModel in a form, the ngModel directive doesn’t just track only the state, it will also update the controls in an angular class state like:
State |
Class if it is true |
Class if it is false |
If the control has been visited |
ng-touched |
ng-untouched |
If the value of the control is changed |
ng-dirty |
ng-pristine |
If the value of the control is valid |
ng-valid |
ng-invalid |
Now coming to the main process, let’s start by creating a new Angular application by using the following command
ng new register
After creating a new Angular application now, we can add bootstrap to the project by using the following command.
npm install bootstrap –save
after adding bootstrap to the library function open index.html add the following code inside of the head tag.
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
After that now we can create a form and perform validation using the template-driven method. Create a new component using the following command
ng generate component employee
Here I have created a new component name as employee; now open employee.component.html and replace the following code as mentioned below.
- <div class="container-fluid">
- <div *ngIf="(showmode=='Register')">
- <form #frmEmployee="ngForm" (ngSubmit)="frmEmployee.form.valid && OnSubmit(frmEmployee)">
- <div class="row">
- <div class="col-md-12">
- <strong>
- <h5>Personal Details </h5>
- </strong>
- </div>
- <div class=" col-md-4 form-group" *ngIf="(ObjConfiguration.showname)">
- <label>Name</label>
- <input type="text" class=" form-control text-uppercase" [(ngModel)]="objEmp.PersonalDetails.Name" name="Username"
- id="Username" maxlength="50" #Username="ngModel" required>
- <small class="text-danger" *ngIf="Username.invalid && (Username.touched || frmEmployee.submitted)"> Name is required</small>
- </div>
- <div class=" col-md-4 form-group" *ngIf="(ObjConfiguration.showdob)">
- <label>DOB</label>
- <input type="date" class="form-control" [(ngModel)]="objEmp.PersonalDetails.Dob" name="Dob" id="Dob"
- #Dob="ngModel" (blur)="OnDate($event)" required >
- <small class="text-danger" *ngIf="Dob.invalid && (frmEmployee.submitted || Dob.touched)">Dob is required!</small>
- <small class="text-danger" *ngIf="Dob.valid && !IsMinDate">Date should be minimum 2019-01-01</small>
- <small class="text-danger" *ngIf="Dob.valid && !IsMaxDate">Date should be maximum 2025-01-01</small>
- </div>
- <div class="col-md-4 form-group" *ngIf="(ObjConfiguration.showmobile)">
- <label>Mobile</label>
- <input type="text" maxlength="10" class="form-control" [(ngModel)]="objEmp.PersonalDetails.Mobile" name="Mobile" id="Mobile"
- #Mobile="ngModel" pattern="^\d{10}$" required>
- <div *ngIf="Mobile.invalid && (frmEmployee.submitted || Mobile.touched)">
- <small class="text-danger" *ngIf="Mobile.errors.required">Mobile Number is required</small>
- <small class="text-danger" *ngIf="Mobile.errors.pattern">Mobile number must be 10 digits</small>
- </div>
- </div>
- <div class="col-md-4 form-group" *ngIf="(ObjConfiguration.showemail)">
- <label>Email ID</label>
- <input type="email" class="form-control" [(ngModel)]="objEmp.PersonalDetails.Email" name="Email" id="Email"
- #Email="ngModel" pattern="^([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5})$" required>
- <div *ngIf="Email.invalid && (frmEmployee.submitted || Email.touched) ">
- <small class="text-danger" *ngIf="Email.errors.required">Email is required</small>
- <small class="text-danger" *ngIf="Email.errors.pattern">Email must be proper format like @ ,.com</small>
- </div>
- </div>
- <div class="col-md-4 form-group" *ngIf="(ObjConfiguration.showgender )">
- <label>Gender</label>
- <select name="Gender" class="form-control" #Gender="ngModel" [(ngModel)]="objEmp.PersonalDetails.Gender"
- required>
- <option *ngFor="let item of Genders" [value]="item">
- {{item}}
- </option>
- </select>
- <small class="text-danger" *ngIf="Gender.invalid && (Gender.touched || frmEmployee.submitted)">Gender is required</small>
- </div>
- </div>
- <hr class="line">
- <div class="row" *ngIf="(ObjConfiguration.showcommdetails)">
- <h5 class="ml-2 col-md-12 mb-3"><strong>Communication Details</strong></h5>
- <div class="col-md-4 form-group" *ngIf="(ObjConfiguration.IsStreet)">
- <label>Street</label>
- <input type="text" class=" form-control text-uppercase" [(ngModel)]="objEmp.CommunicationDetails.Street" name="Street"
- id="Street" maxlength="50" #Street="ngModel" required>
- <small class="text-danger"
- *ngIf="Street.invalid && (Street.touched || frmEmployee.submitted) && ObjConfiguration.IscommMandatory">Street is required</small>
- </div>
- <div class="col-md-4 form-group" *ngIf="(ObjConfiguration.IsArea)" >
- <label>Area</label>
- <input type="text" class=" form-control text-uppercase" [(ngModel)]="objEmp.CommunicationDetails.Area" name="Area" id="Area"
- #Area="ngModel" maxlength="50" required>
- <small class="text-danger" *ngIf="Area.invalid && (Area.touched || frmEmployee.submitted) && ObjConfiguration.IscommMandatory">Area is
- required</small>
- </div>
- <div class="col-md-4 form-group " *ngIf="(ObjConfiguration.IsDistrict)" >
- <label>District</label>
- <input type="text" class="form-control text-uppercase" [(ngModel)]="objEmp.CommunicationDetails.District" name="District"
- id="District" maxlength="50" #District="ngModel" required>
- <small class="text-danger"
- *ngIf="District.invalid && (District.touched || frmEmployee.submitted) && ObjConfiguration.IscommMandatory">District is
- required</small>
- </div>
- <div class="col-md-4 form-group" *ngIf="(ObjConfiguration.IsState)">
- <label>State</label>
- <input type="text" class="form-control text-uppercase" [(ngModel)]="objEmp.CommunicationDetails.State" name="State"
- id="State" maxlength="50" #State="ngModel" required>
- <small class="text-danger" *ngIf="State.invalid && (State.touched || frmEmployee.submitted) && ObjConfiguration.IscommMandatory">State
- is required</small>
- </div>
- <div class="col-md-4 form-group" *ngIf="(ObjConfiguration.IsPincode)" >
- <label>Pincode</label>
- <input type="text" class=" form-control" [(ngModel)]="objEmp.CommunicationDetails.pincode" name="pincode"
- id="pincode" maxlength="6" #pincode="ngModel" required>
- <small class="text-danger"
- *ngIf="pincode.invalid && (pincode.touched || frmEmployee.submitted) && ObjConfiguration.IscommMandatory">pincode is required</small>
- </div>
- <hr class="line">
- </div>
- <div class="text-right m-2 ">
- <button class="btn btn-primary " type="submit">Submit</button>
- <button class="btn btn-danger ml-2" style="float:right" type="reset">Reset</button>
- </div>
- </form>
- </div>
- </div>
And open employee.component.css and place the following code as given below.
- hr {
- background-color: red;
- height: 1px;
- border: 3;
- }
- .buttons {
- display:flex;
- justify-content:flex-end;
- align-items:right;
- }
Create a class file named as employee.ts, and then open model file and replace the following code inside in it.
- export class PersonalDetails {
- public Name: string;
- public Dob: string;
- public Mobile: string;
- public Email: string;
- public Gender: string;
- }
- export class CommunicationDetails {
- public Street: string;
- public Area: string;
- public District: string;
- public State: string;
- public pincode: string;
- }
- export class Employee {
- public PersonalDetails: PersonalDetails = new PersonalDetails();
- public CommunicationDetails: CommunicationDetails = new CommunicationDetails();
- }
- export class Configuration {
- public Isname: boolean;
- public showcommdetails: boolean;
- public IsStreet: boolean;
- public IsArea: boolean;
- public IsDistrict: boolean;
- public IsState: boolean;
- public IsPincode: boolean;
- }
Create a service file named as EmployeeService, open employeeservice.ts file and replace the following code as mentioned below
- import { Injectable } from '@angular/core';
- import { Employee, Configuration } from '../employee';
- import { HttpClient } from '@angular/common/http';
- import { Observable } from 'rxjs';
- @Injectable({
- providedIn: 'root'
- })
- export class EmployeeService {
- public objEmployee = new Employee();
- public Url = '/assets/config.json';
- constructor(private http: HttpClient) {
- }
- public getConfig(): Observable<Configuration> {
- return this.http.get<Configuration>(this.Url);
- }
- }
Then open employee.component.ts file and add the following code. This article is for form validation alone and with the next article we will see how to push data from form to a list.
- import { Component, OnInit } from '@angular/core';
- import { EmployeeService } from '../employee.service';
- import { Employee, Configuration } from 'src/employee';
- @Component({
- selector: 'app-employee',
- templateUrl: './employee.component.html',
- styleUrls: ['./employee.component.css']
- })
- export class EmployeeComponent implements OnInit {
- public showmode: string;
- public objEmp: Employee;
- public ObjConfiguration: Configuration;
- Genders = ['Male', 'Female'];
- constructor(private srvEmployee: EmployeeService) {
- this.showmode = 'Register';
- this.objEmp = new Employee();
- this.ObjConfiguration = new Configuration();
- }
- ngOnInit() {
- this.srvEmployee.getConfig().subscribe(data => this.ObjConfiguration = data);
- }
- }
Create a json file in assets folder by right click-> assets-> create a new file.
Name the new file as config.JSON and open the JSON file and replace the following code as mentioned below.
- {
- "Isname": true,
- "showcommdetails": true,
- "IsStreet":false,
- "IsArea":true,
- "IsDistrict": true,
- "IsState":true,
- "IsPincode": true,
- "showname": true,
- "showdob": true,
- "showmobile": true,
- "showemail" : true,
- "showgender":true,
- "IsnameMandatory": true,
- "IsdobMandatory": true,
- "IsmobileMandatory":true,
- "IsemailMandatory":true,
- "IsgenderMandatory": true,
- "IscommMandatory":true
- }
Finally, run the Angular application by using the command
ng serve -open
Now we can see the output of the application, touch any input field in the form application, for example, touch the input field “name” and we can see the state is changed to name, which is required when the control has been touched.
The next step is click-> submit button and you can see that input fields are required and the form validation has been done using the template-driven method.
I hope this article will be useful for you and in the next article, we can see the pushing of form inputs into a list.