How to Create Custom Form Validator in Angular 8 Application?

How to Create Custom Form Validator in Angular 8 Application?

In this Angular 8 tutorial, you'll learn how to create custom form validator in Angular 8 Application. You will learn to Angular 8 custom validator example step by step. We can simply write custom validation in Angular 8 for reactive form.

Here, I will guide you how to create custom form validator in Angular 8 Application. You will learn to Angular 8 custom validator example step by step. We can simply write custom validation in Angular 8 for reactive form.

Custom validation is a most important thing in programming language. Most of the cases and most of the project you need to create some custom validation so you can reuse it and also write septate code on file then you can use as like pre define validation.

So if you also need to create custom validator in your angular application then follow bellow step to create basic Angular 8 reactive form custom validator.

We will create new custom validator for not contain space on input field. we will not allow space on username. so let's see now it works

Step 1: Install Angular App

Here, in this step you need to create new ng app for this demo. if you have already created then don't create new Angular 8 app.

ng new my-custom-val-app

Step 2: Import FormsModule

If you want to create form in angular app then you need to import FormsModule from @angular/forms library. so let's add following code to app.module.ts file.

src/app/app.module.ts

import { BrowserModule } from '@angular/platform-browser';

import { NgModule } from '@angular/core';

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



import { AppComponent } from './app.component';



@NgModule({

  declarations: [

    AppComponent

  ],

  imports: [

    BrowserModule,

    FormsModule,

    ReactiveFormsModule

  ],

  providers: [],

  bootstrap: [AppComponent]

})

export class AppModule { }

Step 3: Form with ngModel

In this step, we will write code of html form with ngModel. so add following code to app.component.html file.

src/app/app.component.html

<h1>How to Create Custom Validators in Angular 8 - ItSolutionStuff.com</h1>



<form [formGroup]="form" (ngSubmit)="submit()">



    <div class="form-group">

        <label for="username">Username</label>

        <input 

            formControlName="username"

            id="username" 

            type="text" 

            class="form-control">

        <div *ngIf="f.username.touched && f.username.invalid" class="alert alert-danger">

            <div *ngIf="f.username.errors.required">Username is required.</div>

            <div *ngIf="f.username.errors.minlength">Username should be 3 character.</div>

            <div *ngIf="f.username.errors.cannotContainSpace">Username can not contain space.</div>

        </div>

    </div>



    <div class="form-group">

        <label for="password">Password</label>

        <input 

            formControlName="password"

            id="password" 

            type="password" 

            class="form-control">

        <div *ngIf="f.password.touched && f.password.invalid" class="alert alert-danger">

            <div *ngIf="f.password.errors.required">Password is required.</div>

        </div>

    </div>



    <button class="btn btn-primary" type="submit">Submit</button>

</form>

Step 4: updated Ts File

In ts file. we will write submit() and get all input fields values. so let's add following code to app.component.ts file.

src/app/app.component.ts

import { Component } from '@angular/core';

import { FormGroup, FormControl, Validators} from '@angular/forms';

import { UsernameValidator } from './username.validator';



@Component({

  selector: 'app-root',

  templateUrl: './app.component.html',

  styleUrls: ['./app.component.css']

})

export class AppComponent {

  form = new FormGroup({

    username: new FormControl('', [Validators.required, Validators.minLength(3), UsernameValidator.cannotContainSpace]),

    password: new FormControl('', Validators.required)

  });



  get f(){

    return this.form.controls;

  }



  submit(){

    console.log(this.form.value);

  }

}

Step 5: Create Custom Validation File

You need to create custom 'username.validator.ts' file and write code as bellow:

src/app/username.validator.ts

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



export class UsernameValidator {

    static cannotContainSpace(control: AbstractControl) : ValidationErrors | null {

        if((control.value as string).indexOf(' ') >= 0){

            return {cannotContainSpace: true}

        }



        return null;

    }

}

Now you can run your application using following command:

ng serve

I hope it can help you...

Originally published by Hardik Savani at https://www.itsolutionstuff.com

Angular JavaScript WebDev

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Install Angular - Angular Environment Setup Process

Install Angular in easy step by step process. Firstly Install Node.js & npm, then Install Angular CLI, Create workspace and Deploy your App.

Basics of Angular: Part-1

What is Angular? What it does? How we implement it in a project? So, here are some basics of angular to let you learn more about angular. Angular is a Typesc

Upgrade Angular CLI from Angular 8 to Angular 9

In this Angular 9 tutorial is focused on upgrade Angular CLI to 9 in Ubuntu. This example will help you upgrade Angular CLI version for Angular 8 to Angular 9 globally. This article will give you simple example of update Angular 8 to 9. We will look at example of upgrade angular 8 to 9. Let's see bellow example update Angular CLI version 8 to 9.

How to Build an Angular Application with Angular CLI

How to set up the Angular CLI and generate a Trivial App

ReactJS vs Angular vs Vue: Best Javascript Framework For Your Project

ReactJS vs Angular vs Vue: Best Javascript Framework For Your Project. This video covers the key differences between ReactJS, Angular and Vue with respect to the following: Use case, Performance, Data binding, Scripting language, Testing, Community support, Growth curve