Angular 12 Form Validate Empty and White Spaces Tutorial

A common outlook regarding Form validation is to protect from severe spam and get righteous information from the user. If we talk about validation, there are various nuances with which developers have to deal with.

Today, this quick guide will share how to validate empty spaces and white spaces for input fields in the angular app using the custom validator.

We will use the Reactive Forms API to build the simple form with input type text, and use the custom validator to implement no white space allowed validation in the angular input field.

Also, show you how to create the custom validation in angular using the AbstractControl and ValidationErrors APIs.

Angular 12 Reactive Forms No Whitespace Validation Example

  • Step 1: Set Up Angular Environment
  • Step 2: Create Angular App
  • Step 3: Create Custom Validator
  • Step 4: Add White Space Validation
  • Step 5: Create Angular Form
  • Step 6: Run Development Server

Set Up Angular Environment

To begin with this tutorial, first install the node runtime environment and npm package manager on your development machine.

Once the required dependencies are installed, run the command and begin installing the Angular CLI.

npm install -g @angular/cli

Create Angular App

On the other hand, we need to install the new angular app, which can be done through provided command.

ng new ng-demo

Get inside the project directory, after the new app is downloaded.

cd ng-demo

In order to work with forms, open the app.module.ts and import ReactiveFormsModule and FormsModule services from ‘@angular/forms’ package.


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


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

export class AppModule { }

Create Custom Validator

Additionally, we need to create a whitespace.validator.ts file inside the app/ folder. In this file we will use the AbstractControl and ValidationErrors services to create the custom validation for empty space.

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

Add White Space Validation

To implement the validation, we are using the default AppComponent template. Though, you may create the custom component for the same.

Furthermore, import the WhiteSpaceValidator, and FormBuilder, Validators, FormGroup for adding the validation.

Add code in app.component.ts file.

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

import { FormBuilder, Validators, FormGroup } from '@angular/forms';
import { WhiteSpaceValidator } from './whitespace.validator';

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

export class AppComponent {
  
  public fg: FormGroup;
  
  constructor(private fb: FormBuilder) {
    this.fg = fb.group({
      username: ['', [Validators.required, Validators.minLength(2), WhiteSpaceValidator.noWhiteSpace]]
    })
  }
    
  get g(){
    return this.fg.controls;
  }
   
  onSubmit(){
    console.log(this.fg.value);
  }
  
}

Create Form in Angular

At last, we require to create the simple form with username formControlName; you may invoke the form using the FormGroup object and add the validations with the getter method.

Add code in app.component.html file.

<form [formGroup]="fg" (ngSubmit)="onFormSubmit()" novalidate>
  
  <div class="form-group">
    <label>Username</label>
    
    <input type="text" class="form-control mb-3" formControlName="username">

    <div *ngIf="g.username.touched && g.username.invalid" class="alert alert-danger">
      <div *ngIf="g.username.errors?.required">Username is required</div>
      <div *ngIf="g.username.errors?.minlength">Enter atleast 2 characters</div>
      <div *ngIf="g.username.errors?.noWhiteSpace">White and empty spaces are not allowed</div>
    </div>
  </div>

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

Run Development Server

Head over to console and use the provided command to invoke the angular development server.

ng serve

You may use the suggested url to view the app on the browser.

http://localhost:4200

Angular 12 Form Validate Empty and White Spaces Tutorial

Summary

Up to this point, we have explained how to integrate white or empty space validation in angular with reactive forms. We used the AbstractControl API, which is a base class for FormControl, FormGroup, and FormArray.

Moreover, we have learned how to display error messages with a custom validator in angular for empty or white space validation.