Skip to content

Angular, Custom Validator

2017-11-13 09:00:03

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


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;


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

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

  personForm = new FormGroup({

    name: new FormControl('', [
    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');