Sunday, 7 June 2020

Angular Cross Field Validator example

In this demo will do cross field validation, when password and confirm password not match then display error.

To Do: -

1. Add password validator class file inside the shared folder.

2. Import ReactiveFormsModule in the app.module.ts.

3. Use to bootstrap features, register the bootstrap CDN in the index.html.


Lets Start the Project


Step 1: - Create “AngularDemo” folder in the D drive

Step 2: - Open Visual Studio Code

Step 3: - Go to File => Click on Open Folder… => Browse and select created folder “AngularDemo” in the D drive

Step 4: - Type ng new CrossFieldValidator => Press Enter


Step 5: - ? Would you like to add Angular routing? (y/N) => Type => Press Enter


Step 6: - ? Which stylesheet format would you like to use? (Use arrow keys) => Select CSS => Press Enter



Note: - Project created

Step 7: - Go to File => Click on Open Folder… => Browse and select created Project CrossFieldValidator from path D:\AngularDemo\CrossFieldValidator


Step 8: -Project Loaded in Visual Studio Code


Step 9: - Open Terminal => Go to Terminal => Click on New Terminal



Step 10: - Type ng g cl shared/passwordValidator => Press Enter


Step 11: - Open password-validator.ts file inside the shared folder => Copy Past following in password-validator.ts file

import { AbstractControl } from "@angular/forms";

export function PasswordValidator(
  controlAbstractControl
): { [keystring]: boolean } | null {
  const password = control.get("Password");
  const confirmPassword = control.get("ConfirmPassword");
  if (password.pristine || confirmPassword.pristine) {
    return null;
  }
  return password && confirmPassword && password.value != confirmPassword.value
    ? { mismatch: true }
    : null;
}

Step 12: - Open app.module.ts file => Import ReactiveFormModule

import { ReactiveFormsModule from '@angular/forms';



Step 13: - Open app.component.ts file => Copy Past following in app.component.ts file

import { ComponentVERSIONOnInit } from "@angular/core";
import { FormGroupFormBuilderValidators } from "@angular/forms";
import { PasswordValidator } from "./shared/password-validator";

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {
  title = "Cross Field Validator Angular " + VERSION.major;
  formFormGroup;

  constructor(private fbFormBuilder) {}

  ngOnInit() {
    this.form = this.fb.group(
      {
        Password: [""Validators.required],
        ConfirmPassword: [""Validators.required]
      },
      { validators: PasswordValidator //Apply validation on group level not control level
    );
  }

  get password() {
    return this.form.controls["Password"];
  }

  get confirmPassword() {
    return this.form.controls["ConfirmPassword"];
  }
}

Step 14: - Open app.component.html file => Copy Past following in app.component.html file

<div class="container">
  <h1>Hello {{title}}!</h1>
    <form [formGroup]="form">
        <div class="form-group">
            <input type="password" formControlName="Password" class="form-control" placeholder="Enter Password">
            <div *ngIf="password.invalid && password.touched" class="validation-error">
                <div *ngIf="password.errors.required">Password is required.</div>
            </div>
        </div>
        <div class="form-group">
            <input type="password" formControlName="ConfirmPassword" class="form-control" placeholder="Enter Confirm Password">
            <div *ngIf="confirmPassword.invalid && confirmPassword.touched" class="validation-error">
                <div *ngIf="confirmPassword.errors.required">Confirm Password is required.</div>
            </div>
            <div *ngIf="form.errors?.mismatch" class="validation-error">Confirm Password is mismatch.</div>
        </div>
    </form>
</div>

Step 15: - Open Root styles.css file => Copy Past following in Root styles.css file

/* You can add global styles to this file, and also import other style files */
input.ng-touched.ng-invalid {
    border-color:red;
}
.validation-error {
    color : red;
}

Step 16: - To use bootstrap => Open index.html file and add bootstrap CDN link in html head tag.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>CrossFieldValidator</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
  <app-root></app-root>
</body>
</html>

Step 17: - Open Terminal => Type ng serve --o => Press Enter

Add Done

Output

No comments:

Post a Comment