Introduction
In this article, we will learn about validations in the template-driven form in Angular. We will create a simple user registration form and implement some inbuilt validations on it. Along with the inbuilt validations, we will also implement some custom validations to the template-driven form. We will consider the following custom validations for this demo.
- Checking for user name availability
- Password pattern validation
- Match the password entered in two different fields
Take a look at the application in action.

Prerequisites
Source Code
Get the source code from GitHub.
Create the Angular app
Navigate to the folder where you want to create your project file. Open a command window and run the command shown below.
ng new angular-forms-validation --routing=false --style=scss
We are specifying the command to create a new Angular application. The option to create the routing module is set to false and style files extension is set to scss. This command will create the Angular project with the name angular-forms-validation.
Change the directory to the new project and open the project in VS Code using the set of commands shown below.
cd angular-forms-validation
code .
Install Bootstrap
Run the following command to install the bootstrap.
npm install bootstrap --save
Add the following import definition in styles.scss file.
@import "~bootstrap/dist/css/bootstrap.css";
Create the validation service
Run the following command to create a new service.
ng g s services\customvalidation
This command will create a folder named services having two files inside it – customvalidation.service.ts and customvalidation.service.spec.ts. Open customvalidation.service.ts and put the following code inside it.
import { Injectable } from '@angular/core';
import { ValidatorFn, AbstractControl } from '@angular/forms';
import { FormGroup } from '@angular/forms';
@Injectable({
providedIn: 'root'
})
export class CustomvalidationService {
patternValidator(): ValidatorFn {
return (control: AbstractControl): { [key: string]: any } => {
if (!control.value) {
return null;
}
const regex = new RegExp('^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9]).{8,}$');
const valid = regex.test(control.value);
return valid ? null : { invalidPassword: true };
};
}
MatchPassword(password: string, confirmPassword: string) {
return (formGroup: FormGroup) => {
const passwordControl = formGroup.controls[password];
const confirmPasswordControl = formGroup.controls[confirmPassword];
if (!passwordControl || !confirmPasswordControl) {
return null;
}
if (confirmPasswordControl.errors && !confirmPasswordControl.errors.passwordMismatch) {
return null;
}
if (passwordControl.value !== confirmPasswordControl.value) {
confirmPasswordControl.setErrors({ passwordMismatch: true });
} else {
confirmPasswordControl.setErrors(null);
}
}
}
userNameValidator(userControl: AbstractControl) {
return new Promise(resolve => {
setTimeout(() => {
if (this.validateUserName(userControl.value)) {
resolve({ userNameNotAvailable: true });
} else {
resolve(null);
}
}, 1000);
});
}
validateUserName(userName: string) {
const UserList = ['ankit', 'admin', 'user', 'superuser'];
return (UserList.indexOf(userName) > -1);
}
}
The method patternValidator is used to validate the password pattern in our form. The parameter for this method is of type AbstractControl which is a base class for the FormControl. We will use a regular expression to validate the password. This regular expression will check for the following four conditions in the password.
- The password should be a minimum of eight characters long.
- It should have at least one lowercase letter
- It should have at least one upper-case letter
- It should have at least one number
If the password fails the regex check, we will set the invalid password property to true.
The method MatchPassword is used to compare the passwords in two fields. This method will accept two parameters of type string. These parameters represent the names of the fields to be matched. We will get the FormControl for these two fields and then match the values in them. If the values do not match, we will set the password mismatch property to true.
The method userNameValidator is used to verify if the username is already taken or not. This method will accept a parameter of type AbstractControl. We will check if the value of this field is present in a static array, UserList. If the value entered by the user is already present, we will set the userNameNotAvailable property to true. We are using the setTimeout function to invoke this check every two seconds. This will ensure that the error will be thrown after two seconds from the time the user stops typing in the field.
Note. For the sake of simplicity of this article, we are using a static array to search for the availability of user names. Ideally, it should be a service call to the server to search for the value in a database.
Create the User model
Create a new folder called models inside the src/app folder. Add a new file called user.ts inside the models folder. Put the following code in the user.ts file.
export class User {
public name: string;
public email: string;
public username: string;
public password: string;
public confirmPassword: string;
}
Create custom directives
We will create custom directives to implement custom validators for template-driven forms. Run the command shown below to create the passwordPattern directive.
ng g d directives\passwordPattern
This command will create a folder named directives having two files inside it – passwordPattern.directive.ts and passwordPattern.directive.spec.ts. Open passwordPattern.directive.ts and put the following code inside it.
import { Directive } from '@angular/core';
import { NG_VALIDATORS, Validator, AbstractControl } from '@angular/forms';
import { CustomvalidationService } from '../services/customvalidation.service';
@Directive({
selector: '[appPasswordPattern]',
providers: [{ provide: NG_VALIDATORS, useExisting: PasswordPatternDirective, multi: true }]
})
export class PasswordPatternDirective implements Validator {
constructor(private customValidator: CustomvalidationService) { }
validate(control: AbstractControl): { [key: string]: any } | null {
return this.customValidator.patternValidator()(control);
}
}
This directive is used to validate the password pattern. We will implement the Validator interface on the class PasswordPatternDirective. We will override the validate method which accepts a parameter of type AbstractControl i.e. the control we want to validate. We will then invoke the patternValidator method from the service.
Run the command shown below to create a matchPassword directive.
ng g d directives\matchPassword
Open matchPassword.directive.ts and put the following code inside it.
import { Directive, Input } from '@angular/core';
import { NG_VALIDATORS, Validator, ValidationErrors, FormGroup } from '@angular/forms';
import { CustomvalidationService } from '../services/customvalidation.service';
@Directive({
selector: '[appMatchPassword]',
providers: [{ provide: NG_VALIDATORS, useExisting: MatchPasswordDirective, multi: true }]
})
export class MatchPasswordDirective implements Validator {
@Input('appMatchPassword') MatchPassword: string[] = [];
constructor(private customValidator: CustomvalidationService) { }
validate(formGroup: FormGroup): ValidationErrors {
return this.customValidator.MatchPassword(this.MatchPassword[0], this.MatchPassword[1])(formGroup);
}
}
This directive is used to validate if the passwords entered in two fields match or not. This directive will accept an input of the type string array, which contains the fields to match. We will override the validate method and pass the parameter of type FormGroup. We will then invoke the MatchPassword method from the service.
Run the command shown below to create the validateUserName directive.
ng g d directives\validateUserName
Open validateUserName.directive.ts and put the following code inside it.

Chittaranjan SwainPosted Dec 23, 2019, 4:38 AM
Nice article.