Angular, Custom Validator

This post is a continuation of post where we create simple reactive form, here I will “describe” how to create custom directive. Of course here we have only my notes. More about Custom Validator you will find in Angular Guide Keep in mind that here you will not find all files to establish project, here we have only part related with validators



username.validator.ts

here we have simple custom validator that will check if user name is not against some strange rule: “no admin word in the name”

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

export class UsernameValidator {

  static cannotContainsAdminWord(control: AbstractControl): ValidationErrors | null {
    if ((control.value as string).toLowerCase().indexOf("admin") >= 0) {
      return {cannotContainsAdminWord: "No admin in user name!"}
    }
    return null;
  }
}

person-detail.component.ts

import { Component } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import {UsernameValidator} from "./username.validator";

@Component({
  selector: 'app-person-detail',
  templateUrl: './person-detail.component.html',
  styleUrls: ['./person-detail.component.css']
})
export class PersonDetailComponent {

  personForm = new FormGroup({

    name: new FormControl('', [
      Validators.required,
      Validators.minLength(5),
      UsernameValidator.cannotContainsAdminWord
    ]),
    email: new FormControl('email@email'),

    address: new FormGroup({
      city: new FormControl('Toruń'),
      street: new FormControl('Kopernika'),
      houseNumber: new FormControl('1473'),
    })

  });

  get name() {
    return this.personForm.get('name');
  }

}