Angular 8 Custom Validation Tutorial with Examples

By Digamber Rawat Last updated on
In this Angular 8 tutorial, we will look at how to create custom validators using Angular 8 Reactive Forms. 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 8 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 8 is pretty simple and easy, like creating other functions. Custom validator takes AbstractControl as a parameter and returns an object in the form of `key: value` pair if the validation fails.

Create Custom Validator in Angular 8

In the following example, we’ll check how does the custom validation work in Angular 8. 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 8.

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 8 Component

Let’s understand how to use custom validation in Angular 8 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/urlvalidator.validator.ts";

@Component({
  ...
  ...
  ...
})

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 {
      alert('URL is valid')
    }
  }

}

Showing Custom Validation Errors

Now, we’ll learn to show custom validators errors using Angular 8 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 8 custom validator.

  <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>

You can check out below how does custom validation works in Angular 8:

DEMO

Digamber Rawat
Digamber Rawat

Full stack developer with a passion for UI/UX design. I create beautiful and useful digital products to solve people’s problem and make their life easy.

Hire Me