Welcome folks today in this blog post we will be doing reactive forms
validation in angular 14 and bootstrap 5 in browser using typescript. All the full source code of the application is shown below.
Get Started
In order to get started you need to create a new angular project using the below commands as shown below
ng new angularvalidation
cd angularvalidation
Now we need to install the bootstrap
5 dependency inside the angular app by executing the below command as shown below
npm i bootstrap
And after this you need to go to styles.css
file and add the below line to include the bootstrap css
style.css
1 |
@import "~bootstrap/dist/css/bootstrap.css" |
And now you need to go to tsconfig.json
file and change the value of the noPropertyAccessFromIndexSignature
property from true to false as shown below
And now after this we need to include the reactive
form dependency inside the app.module.ts
file of your angular project as shown below
app.module.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import {ReactiveFormsModule} from '@angular/forms' import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, ReactiveFormsModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } |
As you can see we have imported the ReactiveFormsModule
from the angular forms core module and then included it inside the imports array
And now you need to go to app.component.html
file of your project to write the basic bootstrap 5 form as shown below
app.component.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<div class="container"> <div class="row"> <div class="col-md-6 offset-md-3"> <form> <div class="form-group"> <label for="firstname">First Name</label> <input type="text" class="form-control"> </div> <div class="form-group"> <label for="lastname">Last Name</label> <input type="text" class="form-control"> </div> <div class="form-group"> <label for="email">Email Address</label> <input type="email" class="form-control"> </div> <div class="form-group"> <label for="password">Password</label> <input type="password" class="form-control"> </div> <div class="form-group"> <button class="btn btn-primary">Register</button> </div> </form> </div> </div> </div> |
As you can see that we have the four form input fields
where we have the firstname,lastname,email and the password we have attached some bootstrap classes to it to make it look good in the browser
And now you need to go to app.component.ts
file and copy paste this code as shown below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import { Component } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { registerForm!:FormGroup title = 'angularvalidate'; submitted=false constructor(private formBuilder:FormBuilder){} } |
As you can see that we are importing the required libraries from the angular core form module at the very top. We are importing the FormBuilder,FormGroup and different Validators which are required for making the validations to the input fields. Apart from that we also have variables first one is the formGroup type variable and then we have the boolean parameter which is submitted which actually tracks whether the form is validated or not. The default value for submitted is false. And in the constructor we have passed the formGroup variable reference.
And now again you need to go back to the app.component.html
file and now we will be attaching some attributes
to the form as shown below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<div class="container"> <div class="row"> <div class="col-md-6 offset-md-3"> <form (submit)="onSubmit()" [formGroup]="registerForm"> <div class="form-group"> <label for="firstname">First Name</label> <input type="text" class="form-control"> </div> <div class="form-group"> <label for="lastname">Last Name</label> <input type="text" class="form-control"> </div> <div class="form-group"> <label for="email">Email Address</label> <input type="email" class="form-control"> </div> <div class="form-group"> <label for="password">Password</label> <input type="password" class="form-control"> </div> <div class="form-group"> <button class="btn btn-primary">Register</button> </div> </form> </div> </div> </div> |
As you can see we have attached the onSubmit
event handler to the form. When you press the register button this function will automatically execute and also we have the attached the formGroup parameter as well.
Writing the Different Validators for Input Fields
Now guys we will be writing the different validations that this reactive form offers for validating different data. Now inside the app.component.ts
file just copy paste the below code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
import { Component } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { registerForm!:FormGroup title = 'angularvalidate'; submitted=false constructor(private formBuilder:FormBuilder){ } ngOnInit(){ this.registerForm = this.formBuilder.group({ firstName:['',[Validators.required,Validators.minLength(4)]], lastName:['',Validators.required], email:['',[Validators.required,Validators.email]], password:['',[Validators.required,Validators.minLength(8)]] }) } } |
As you can see we have added the lifecycle method which is ngOnInit()
which automatically executes when you load the page and inside this we are making the new object of formBuilder
and attaching it to the current form in the DOM. And here we are using the group()
method to attach different validations to the input fields. These are required, minLength and also valid email address.
Showing Error Messages in HTML
Now guys we need to go to app.component.html
file and add the error messages and attach these attributes and the error classes as shown below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
<div class="container"> <div class="row"> <div class="col-md-6 offset-md-3"> <form (submit)="onSubmit()" [formGroup]="registerForm"> <div class="form-group"> <label for="firstname">First Name</label> <input [ngClass]="{'is-invalid':submitted && registerForm.controls.firstName.errors}" formControlName="firstName" type="text" class="form-control"> <div *ngIf="submitted && registerForm.controls.firstName.errors" class="text-danger"> <div *ngIf="submitted && registerForm.controls.firstName.errors.required"> First Name is required </div> <div *ngIf="submitted && registerForm.controls.firstName.errors.minlength"> First Name Should be atleast 4 characters </div> </div> </div> <div class="form-group"> <label for="lastname">Last Name</label> <input [ngClass]="{'is-invalid':submitted && registerForm.controls.lastName.errors}" formControlName="lastName" type="text" class="form-control"> <div *ngIf="submitted && registerForm.controls.lastName.errors" class="text-danger"> <div *ngIf="submitted && registerForm.controls.lastName.errors.required"> Last Name is required </div> </div> </div> <div class="form-group"> <label for="email">Email Address</label> <input [ngClass]="{'is-invalid':submitted && registerForm.controls.email.errors}" formControlName="email" type="email" class="form-control"> <div *ngIf="submitted && registerForm.controls.email.errors" class="text-danger"> <div *ngIf="submitted && registerForm.controls.email.errors.required"> Email Address is required </div> <div *ngIf="submitted && registerForm.controls.email.errors.email"> Email Address is not Valid </div> </div> </div> <div class="form-group"> <label for="password">Password</label> <input [ngClass]="{'is-invalid':submitted && registerForm.controls.password.errors}" formControlName="password" type="password" class="form-control"> <div *ngIf="submitted && registerForm.controls.password.errors" class="text-danger"> <div *ngIf="submitted && registerForm.controls.password.errors.required"> Password is required </div> <div *ngIf="submitted && registerForm.controls.password.errors.minlength"> Password should be atleast 8 characters </div> </div> </div> <div class="form-group"> <button class="btn btn-primary">Register</button> </div> </form> </div> </div> </div> |
As you can see in the above code we have attached the bootstrap error classes based upon certain error messages occured we are showing the required messages for different errors. We have done this for every input fields.
Now we need to write the onSubmit()
method inside the app.component.ts
file as shown below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
import { Component } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { registerForm!:FormGroup title = 'angularvalidate'; submitted=false constructor(private formBuilder:FormBuilder){ } ngOnInit(){ this.registerForm = this.formBuilder.group({ firstName:['',[Validators.required,Validators.minLength(4)]], lastName:['',Validators.required], email:['',[Validators.required,Validators.email]], password:['',[Validators.required,Validators.minLength(8)]] }) } onSubmit(){ this.submitted = true if(this.registerForm.invalid){ return } alert("Success") } } |
As you can see guys we have added the onSubmit()
method inside this we are checking if any errors there then we return else we are showing the success message as shown below