Angular 16 Custom Validation Tutorial with Examples

Last Updated on by in Angular
In this Angular custom validation example tutorial, we will look at how to create a custom validators in Angular 16 using reactive forms API.Angular is a robust front-end framework; it comes with powerful built-in validators like minLength, maxLength, pattern, and required.

Sometimes we have to deal with more difficult validation cases in real-world scenario thats where the custom validators help us to deal with the situation.

Implementing custom validators using Angular Reactive Forms is very easy. Custom validators are just like functions which we often use in our day to day programming tasks. You can create custom validators for any given scenario.

Creating custom validation in Angular is pretty simple and easy, like creating other functions.

Let us follow the steps mentioned in this guide.

Create Angular Project

First, Install Angular CLI. Open a command prompt or terminal.

Run the following command to install Angular CLI globally:

npm install -g @angular/cli

Create a new Angular app using given command.

ng new angular-demo

Navigate to the project folder:

cd angular-demo

No Property Access From Index Signature

To resolve error:

Property ‘xxxName’ comes from an index signature, so it must be accessed with [‘xxxName’]

This setting makes sure profound consistency between accessing a field via the “dot” (obj.key) syntax, and “indexed” (obj["key"]) and the way which the property is declared in the type.

Without this flag, TypeScript will allow you to use the dot syntax to access fields which are not defined:

Make sure to set noPropertyAccessFromIndexSignature property to false under compilerOptions in tsconfig.json file:

"compilerOptions": {
 ...
 ...
   "strict": false,
   "noPropertyAccessFromIndexSignature": false,
 ...
 ...
}

Create Custom Validator in Angular

In the following example, we’ll check how does the custom validation work in Angular.

In order to check this out, we need to create a custom validator using Reactive Forms which will validate if the URL starts with https and contains .me.

Let’s create a folder by the name of validators in the application root and then create a file by the name of validators/custom.validators.ts in the same folder.

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

export function urlValidator(control: AbstractControl) {
  if (!control.value.startsWith('https') || !control.value.includes('.me')) {
    return { urlValid: true };
  }
  return null;
}

We define the custom function by the name of urlValidator and passed the control: AbstractControl parameter inside the function we are checking if the URL starts with https and contains .me.

As you can see we are using AbstractControl class, this class is also known as the core class of form groups, form arrays and form controls. It allows us to access the form control value in Angular.

If the custom validation passes the validation, then it returns null otherwise if the validation fails, then it will return an object with the error name.

Using Custom Validator in Angular Component

Let’s understand how to use custom validation in Angular application. First, import the custom validation service and Reactive Forms services in app.component.ts.

import { Component } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
import { urlValidator } from './validators/custom.validators';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})

export class AppComponent {
  constructor(public fb: FormBuilder) {}

  validatorForm = this.fb.group({
    url: ['', [Validators.required, urlValidator]], // custom validator name
  });

  get url() {
    return this.validatorForm.get('url');
  }

  // Submit Registration Form
  onSubmit() {
    if (!this.validatorForm.valid) {
      alert('Please enter the correct url!');
      return false;
    } else {
      return alert('URL is valid');
    }
  }
}

Add Forms Module

In this step, you have to register the form modules in app.module.ts file.

import { FormsModule, ReactiveFormsModule } from '@angular/forms';

@NgModule({
  declarations: [],
  imports: [
    FormsModule,
    ReactiveFormsModule,
  ],
  providers: [],
  bootstrap: []
})

export class AppModule {}

Showing Custom Validation Errors

Now, we’ll learn to show custom validators errors using reactive forms. As you can see, we are taking the help of url getter to access the url form control.

Define the ERROR HTML and access the urlValid via custom validation method to show the errors using Angular custom validator.

Add code in app.component.html file.

<form [formGroup]="validatorForm" (ngSubmit)="onSubmit()">
  <input type="text" formControlName="url" />

  <!-- error block -->
  <div *ngIf="url.errors?.['urlValid']">
    <sup>*</sup>Use should start with https and must end with .me :)
  </div>

  <button type="submit">Check the URL</button>
</form>

Run Angular App

Run the following command to serve your app locally:

ng serve --open

We can now see your Angular app running on:

http://localhost:4200/