Password Strength Pipe in Angular

Introduction

In this article, we will learn how to create a pipe to check strength of a password in Angular Application.

Prerequisites

  • Basic Knowledge of Angular 2 or higher
  • Visual Studio Code
  • Node and NPM installed
  • Bootstrap (Optional)

Create an Angular project by using the following command.

ng new angapp

Now install Bootstrap by using the following command.

npm install bootstrap --save

Now open the styles.css file and add the Bootstrap file reference. To add a reference in the styles.css file, add this line.

@import '~bootstrap/dist/css/bootstrap.min.css';

Create a Password Strength Pipe

Now, create a custom pipe by using the following command.

ng generate pipe PasswordStrength

Now open the password.pipe.ts file and add the following code

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({ name: 'passwordStrength' })
export class PasswordStrengthPipe implements PipeTransform {
  transform(password: string): string {
    if (!password) return '';

    if (password.length < 6) {
      return 'Weak';
    } else if (password.length < 10) {
      return 'Medium';
    } else if(password.length < 15 ) {
      return 'Strong';
    }
    else  (password.length < 20 ) 
    {
			return 'Very Strong';
  }
}
}

Now, create a new component by using the following command.

ng g c actionmenu

Now open searchlist.actionmenu.html file and add the following code.

<div class="container" style="margin-top:10px;margin-bottom: 24px;">
    <p>{{ 'Password!123' | passwordStrength }}</p>
    <p>{{ '123456' | passwordStrength }}</p>
</div>

Now open app.component.html file and add the following code.

<div class="container" style="margin-top:10px;margin-bottom: 24px;">
  <div class="col-sm-12 btn btn-info">
    Password Strength Pipe in Angular
  </div>
</div>
<app-actionmenu></app-actionmenu>

Now run the application using npm start and check the result.

Output

Summary

In this article, we learned how to how to create a pipe to check strength of a password in Angular Application.