Compare Password with Validation Error in Angular

 

In this tutorial, we are going to learn how to implement password comparison with validation in Angular. When building authentication systems, ensuring that the user enters a matching password and confirm password is crucial. Angular provides a robust way to handle form validation, including custom validators to compare passwords.

Setting Up an Angular Form with Password Validation

Before we start, let’s set up a basic Angular form using Reactive Forms to validate password fields.

Step 1: Create an Angular Component

If you haven’t already created a component for the login or signup form, use the following command:

ng generate component password-validation

Step 2: Import Required Modules

Modify app.module.ts to import ReactiveFormsModule:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { ReactiveFormsModule } from '@angular/forms';
import { PasswordValidationComponent } from './password-validation/password-validation.component';

@NgModule({
  declarations: [
    AppComponent,
    PasswordValidationComponent
  ],
  imports: [
    BrowserModule,
    ReactiveFormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}

Step 3: Create the Form with Password Fields

Modify password-validation.component.ts to define the form:

import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators, AbstractControl } from '@angular/forms';

@Component({
  selector: 'app-password-validation',
  templateUrl: './password-validation.component.html',
  styleUrls: ['./password-validation.component.css']
})
export class PasswordValidationComponent {
  passwordForm: FormGroup;

  constructor(private fb: FormBuilder) {
    this.passwordForm = this.fb.group({
      password: ['', [Validators.required, Validators.minLength(6)]],
      confirmPassword: ['', Validators.required]
    }, { validator: this.passwordMatchValidator });
  }

  passwordMatchValidator(control: AbstractControl) {
    const password = control.get('password')?.value;
    const confirmPassword = control.get('confirmPassword')?.value;
    if (password !== confirmPassword) {
      control.get('confirmPassword')?.setErrors({ mismatch: true });
    } else {
      return null;
    }
  }

  onSubmit() {
    if (this.passwordForm.valid) {
      console.log('Form Submitted', this.passwordForm.value);
    }
  }
}

Step 4: Create the HTML Form

Modify password-validation.component.html:

<form [formGroup]="passwordForm" (ngSubmit)="onSubmit()">
  <label>Password:</label>
  <input type="password" formControlName="password">
  <div *ngIf="passwordForm.controls.password.errors?.required">Password is required.</div>
  <div *ngIf="passwordForm.controls.password.errors?.minlength">Password must be at least 6 characters.</div>

  <label>Confirm Password:</label>
  <input type="password" formControlName="confirmPassword">
  <div *ngIf="passwordForm.controls.confirmPassword.errors?.required">Confirm Password is required.</div>
  <div *ngIf="passwordForm.controls.confirmPassword.errors?.mismatch">Passwords do not match.</div>

  <button type="submit" [disabled]="passwordForm.invalid">Submit</button>
</form>

Step 5: Styling the Form (Optional)

Modify password-validation.component.css:

input {
  display: block;
  margin-bottom: 10px;
}
div {
  color: red;
  font-size: 12px;
}

Conclusion

In this tutorial, we have learned how to compare passwords with validation in Angular using Reactive Forms. The key points covered include:

  • Creating a form using FormGroup and FormBuilder.
  • Implementing a custom validator to check if passwords match.
  • Displaying error messages dynamically.

This method ensures a smooth user experience and prevents incorrect password entries. 

Happy coding! 🚀

Post a Comment

0 Comments