Angular 16 Reactive Forms White / Empty Spaces Validation

Last updated on: by Digamber

Angular white space validation tutorial; In this tutorial, you will learn how to add white space or empty space validation in angular form.

Also, we will explain how to add validation for no space allowed on the HTML input field using the reactive forms in angular application.

A form is the primary component of any application and is best used for collecting information from the users. A form is validated so that wrong information can not be submitted.

Earlier, we have covered other aspects of angular form validation. In this Angular custom whitespace validation example.

We will reveal how to integrate no space allow to form input field in angular application from scratch.

You can comfortably use this tutorial for angular 15, 14, 12, 11, 10, 9, and 8 versions.

How to Implement White and Empty Spaces Validation in Angular 16 Form

  • Step 1: Install Angular CLI
  • Step 2: Download Angular Project
  • Step 3: Add Reactive Forms Module
  • Step 4: Custom White Space Not Allowed Validation
  • Step 5: Update TypeScript Template
  • Step 6: Update HTML Template
  • Step 7: Start Angular App

Install Angular CLI

In the first step, you need to begin by adding the Angular command-line interface commonly known as the CLI.

sudo npm install -g @angular/cli

Download Angular Project

Now, you are ready to create the a new angular application, type the command and hit enter to install the app.

ng new ng-demo

After you executed the provided command, the cli will create a skeleton project within the ng-demo folder.

Move to the app’s project folder.

cd ng-demo

To resolve error:

No Property Access From Index Signature:

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": {
// ...
// ...
   "noPropertyAccessFromIndexSignature": false,
// ...
// ...
}

Add Reactive Forms Module

Next, make sure to import the reactive forms module and forms module in order to work with angular form.

So, add the given code in the src/app/app.module.ts.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { ReactiveFormsModule, FormsModule } from '@angular/forms';
@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, ReactiveFormsModule, FormsModule],
  providers: [],
  bootstrap: [AppComponent],
})
export class AppModule {}

Custom White Space Not Allowed Validation

To create a custom white space or empty space not allowed validator. You have to create the nameWhiteSpace.validator.ts file inside the src/app/ folder.

import { AbstractControl, ValidationErrors } from '@angular/forms';  
    
export class NameWhiteSpace {  
    static noSpaceAllowed(control: AbstractControl) : ValidationErrors | null {  
        if((control.value as string).indexOf(' ') >=0){  
            return {noSpaceAllowed: true}  
        }  
    
        return null;  
    }  
}

Update TypeScript Template

To create the form you need to import FormBuilder, FormGroup, Validators from ‘@angular/forms’.

Also, import the previously created custom validator NameValidator from from ‘./nameWhiteSpace.validator’.

Update the provided code in src/app/app.component.ts file.

import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { NameWhiteSpace } from './nameWhiteSpace.validator';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {
  public myForm: FormGroup;
  constructor(private formBuilder: FormBuilder) {
    this.myForm = formBuilder.group({
      name: [
        '',
        [
          Validators.required,
          Validators.minLength(4),
          NameWhiteSpace.noSpaceAllowed,
        ],
      ],
    });
  }
  get m() {
    return this.myForm.controls;
  }
  onSubmit() {
    console.log(this.myForm.value);
  }
}

Update HTML Template

In this step, you will use the given code to create the form. Define the inline validation using the getter method.

We will add required, minimum length, and empty space not allowed validation in the open the src/app/app.component.html file.

<div class="container mt-5">
  <h2>Whitespace Form Validation in Angular Example</h2>
  <form [formGroup]="myForm" (ngSubmit)="onSubmit()" novalidate>
    <div class="form-group">
      <label>Enter Name</label>
      <input type="text" formControlName="name" class="form-control mb-2" />
      <div *ngIf="m.name.touched && m.name.invalid" class="alert alert-danger">
        <div *ngIf="m.name.errors?.required">Please provide name</div>
        <div *ngIf="m.name.errors?.minlength">Name must be 4 characters</div>
        <div *ngIf="m.name.errors?.noSpaceAllowed">Whitespace is not allowed</div>
      </div>
    </div>
    <div class="d-grid mt-3">
      <button class="btn btn-dark" type="submit">Save</button>
    </div>
  </form>
</div>

Start Angular App

Finally, you have to run the app development server, use the suggested command.

http://localhost:4200

Angular 12 Reactive Forms White / Empty Spaces Validation

Conclusion

This angular tutorial taught us how to create and set up reactive form using the ReactiveFormsModule API and create a custom validator to validate the name for whitespace and empty spaces.

positronX.io - Tamso Ma Jyotirgamaya
Digamber

A Full-stack developer with a passion to solve real world problems through functional programming.