Sunday 7 June 2020

Angular Custom Validator example

In this demo will do custom validation, name field admin, test and abc keyword not allowed to enter.

To Do: -

1. Add name 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 CustomValidator => 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 CustomValidator from path D:\AngularDemo\CustomValidator


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/nameValidator => Press Enter



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

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

export function ForbiddenNameValidator(nameRegExp): ValidatorFn {
  return (controlAbstractControl): { [keystring]: any } => {
    const forbidden = name.test(control.value.toLowerCase());
    return forbidden ? { 'forbiddenName' : { value: control.value } } : 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 { ForbiddenNameValidator } from "./shared/name-validator";

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

  constructor(private fbFormBuilder) {}

  ngOnInit() {
    this.form = this.fb.group({
      FirstName : ['',[Validators.required,Validators.minLength(3), ForbiddenNameValidator(/admin|test|abc/)]]
    });
  }

  get firstname(){
    return this.form.controls['FirstName'];
  };
}

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 formControlName="FirstName" class="form-control" placeholder="Enter Name">
      <div *ngIf="firstname.invalid && firstname.touched" class="validation-error">
        <div *ngIf="firstname.errors.required">Name is required.</div>
        <div *ngIf="firstname.errors.minlength">Name must be at least 3 characters long.</div>
        <div *ngIf="firstname.errors.forbiddenName"> {{firstname.errors.forbiddenName.value}} name not allowed.
        </div>
      </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>CustomValidator</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

Angular Conditional Validator example

No comments:

Post a Comment