Angular 12 Reactive Forms White / Empty Spaces Validation

Last updated on: by Editorial Team

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 12, 11, 10, 9, and 8 versions.

How to Implement White and Empty Spaces Validation in Angular 12 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.

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

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 { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

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


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

export class AppModule { }

Custom White Space Not Allowed Validation

In this step you need to create app/name.validator.ts file and create the custom class using the AbstractControl and ValidationErrors, this class will help to add the custom validation in angular app.

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

Update TypeScript Template

To create the form you need to import FormBuilder, FormGroup, Validators from ‘@angular/forms’, alos import the previously created custom validator NameValidator from from ‘./name.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 { NameValidator } from './name.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(3), NameValidator.noWhiteSpace]]
    })
  }
    
  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?.noWhiteSpace">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.

ng serve

Open browser, type given url and hit enter to test the validation.

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.