Skip to content
Readerstacks logo Readerstacks
  • Home
  • Softwares
  • Angular
  • Php
  • Laravel
  • Flutter
Readerstacks logo
Readerstacks
Password and confirm password validation in angular

Password and confirm password validation in angular 14 ?

Aman Jain, September 9, 2022September 9, 2022

Angular 14 provides built-in library for validation but it doesn’t have built in validation for password and confirm password. Angular 14 has release and we are excited to work with new feature so i am also updating the most search article with latest version of angular. so in this tutorial i am going to explain how can we make custom validation for this same as angular built-in validations. Confirm password most useful utility when we create a register form and we want to make sure user is typing the correct password so in future user is sure for the confirmed password.

In this example we will create a simple form with password and confirm password field and then will create a Custom form validator class in which we will implement the match functionality for both the fields.

Also read about How to make custom validation in angular reactive form ? and How to generate component in angular cli?

Let’s start the Password Confirm Validation in Angular 14 with simple steps.

Step 1: Create a class CustomValidator

In this step, we are creating a class where we can define or all custom validators.

/src/app/providers/CustomValidators.ts

import {
  AbstractControl,
  ValidatorFn,
  FormControl,
  FormGroup
} from '@angular/forms';

export class CustomValidators {
  constructor() {}

  static onlyChar(): ValidatorFn {
    return (control: AbstractControl): { [key: string]: boolean } | null => {
      if (control.value == '') return null;

      let re = new RegExp('^[a-zA-Z ]*$');
      if (re.test(control.value)) {
        return null;
      } else {
        return { onlyChar: true };
      }
    };
  }
  static mustMatch(controlName: string, matchingControlName: string) {
    return (formGroup: FormGroup) => {
      const control = formGroup.controls[controlName];
      const matchingControl = formGroup.controls[matchingControlName];

      if (matchingControl.errors && !matchingControl.errors.mustMatch) {
        return;
      }

      // set error on matchingControl if validation fails
      if (control.value !== matchingControl.value) {
        matchingControl.setErrors({ mustMatch: true });
      } else {
        matchingControl.setErrors(null);
      }
      return null;
    };
  }
}

So, as in the example above we have created two methods onlyChar and mustMacth. Then, in mustMatch we are fetching the control from formGroup and checking for password.

Step 2 : Add form to component and import custom validation

We are using FormGroup and FormControl to declare the reactive form in angular. Validators library to validate the fields. As you can see in below code we have imported FormControl, FormGroup, Validators from ‘@angular/forms’.

Next, we are importing CustomValidator class from file ‘./providers/CustomValidators’.

In next line we have created a FormGroup and assigned the controls to it.

src/app/app.component.ts

import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';

// import custom validator  class
import { CustomValidators } from './providers/CustomValidators';

@Component({
  selector: 'my-app',
  templateUrl: 'app.component.html'
})
export class AppComponent implements OnInit {
  success = '';
  registerForm = new FormGroup(
    {
      firstName: new FormControl('', [Validators.required]),
      lastName: new FormControl('', [Validators.required]),
      email: new FormControl('', [Validators.required, Validators.email]),
      password: new FormControl('', [
        Validators.required,
        Validators.minLength(8)
      ]),
      confirmPassword: new FormControl('', [Validators.required])
    },

    CustomValidators.mustMatch('password', 'confirmPassword') // insert here
  );

  submitted = false;

  constructor() {}

  ngOnInit() {}

  // convenience getter for easy access to form fields
  get f() {
    return this.registerForm.controls;
  }

  onSubmit() {
    this.submitted = true;

    // stop here if form is invalid
    if (this.registerForm.invalid) {
      return;
    }

    this.success = JSON.stringify(this.registerForm.value);
  }
}


Step 3 : Create html file and bind FormGroup to form

Now, we are ready to bind our FormGroup to html form and FormControl to the fields.

<!-- main app container -->
<div class="readersack">
  <div class="container">
    <div class="row">
      <div class="col-md-6 offset-md-3">
        <h3>Angular 14 Reactive Form Validation</h3>
        {{success?"Success - "+success:""}}
        <form [formGroup]="registerForm" (ngSubmit)="onSubmit()">
          <div class="form-group">
            <label>First Name</label>
            <input type="text" formControlName="firstName" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.firstName.errors }" />
            <div *ngIf="submitted && f.firstName.errors" class="invalid-feedback">
              <div *ngIf="f.firstName.errors.required">First Name is required</div>
            </div>
          </div>
          <div class="form-group">
            <label>Last Name</label>
            <input type="text" formControlName="lastName" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.lastName.errors }" />
            <div *ngIf="submitted && f.lastName.errors" class="invalid-feedback">
              <div *ngIf="f.lastName.errors.required">Last Name is required</div>
            </div>
          </div>
          <div class="form-group">
            <label>Email</label>
            <input type="text" formControlName="email" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.email.errors }" />
            <div *ngIf="submitted && f.email.errors" class="invalid-feedback">
              <div *ngIf="f.email.errors.required">Email is required</div>
              <div *ngIf="f.email.errors.email">Email must be a valid email address</div>
            </div>
          </div>
          <div class="form-group">
            <label>Password</label>
            <input type="password" formControlName="password" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.password.errors }" />
            <div *ngIf="submitted && f.password.errors" class="invalid-feedback">
              <div *ngIf="f.password.errors.required">Password is required</div>
              <div *ngIf="f.password.errors.minlength">Password must be at least 6 characters</div>
            </div>
          </div>
          <div class="form-group">
            <label>Confirm Password</label>
            <input type="password" formControlName="confirmPassword" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.confirmPassword.errors }" />
            <div *ngIf="submitted && f.confirmPassword.errors" class="invalid-feedback">
              <div *ngIf="f.confirmPassword.errors.required">Confirm Password is required</div>
              <div *ngIf="f.confirmPassword.errors.mustMatch">Password and confirm not match</div>
            </div>
          </div>
          <div class="form-group">
            <button class="btn btn-primary">Register</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</div>

<!-- credits -->
<div class="text-center">
  <p>
    <a href="#" target="_top">Angular
      12 - Reactive Forms Validation and confirm password Example</a>
  </p>
  <p>
    <a href="https://readerstacks.com" target="_top">readerstacks.com</a>
  </p>
</div>


Live Code and download

Share this:

  • Facebook
  • X

Related

Javascript Angular angularconfirmpasswordvalidation

Post navigation

Previous post
Next post

Related Posts

How many type of methods in Restful api?

August 28, 2021September 1, 2021

Restful api is very useful today while creating a mobile application or web application. Restful api or Http request methods There is 4 types of method of http request. Post Get Put Delete Patch 1. Post method Post method is widely used to fetch the content of a form or…

Share this:

  • Facebook
  • X
Read More
Javascript Angular ngClass conditional class Example

Angular ngClass conditional class Example

October 8, 2022November 8, 2023

In this blog post, we’ll explore Angular ngClass conditional class Example in component’s styles based on certain conditions. Sometimes in our application we want dynamically change the color, size, font, background images so Angular provides various ways to conditionally apply classes and style to elements. We’ll discuss how to use…

Share this:

  • Facebook
  • X
Read More
Javascript Angular conditional validation in reactive forms

Angular conditional validation in reactive forms

September 26, 2022November 8, 2023

This post covers the basis of angular conditional validation in reactive forms. By the end of this post, the reader will know how to set up a simple form and validate it according to different criteria. Conditional validation is when the validity of a form control is determined by something…

Share this:

  • Facebook
  • X
Read More

Leave a ReplyCancel reply

Aman Jain
Aman Jain

With years of hands-on experience in the realm of web and mobile development, they have honed their skills in various technologies, including Laravel, PHP CodeIgniter, mobile app development, web app development, Flutter, React, JavaScript, Angular, Devops and so much more. Their proficiency extends to building robust REST APIs, AWS Code scaling, and optimization, ensuring that your applications run seamlessly on the cloud.

Categories

  • Angular
  • CSS
  • Dart
  • Devops
  • Flutter
  • HTML
  • Javascript
  • jQuery
  • Laravel
  • Laravel 10
  • Laravel 9
  • Mysql
  • Php
  • Softwares
  • Ubuntu
  • Uncategorized

Archives

  • December 2023
  • November 2023
  • October 2023
  • July 2023
  • March 2023
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021

Recent Posts

  • How to Call Controller Method from Another Controller in Laravel ?
  • How to Get Domain Name in Laravel ?
  • How to Append Query String to Route in Laravel ?
  • How to Append URL Query Params to Pagination Laravel ?
  • How to Get Today Records in Laravel ?
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version