How To Add White Space Validation In Angular

In this article, we will learn how to add white space validation in angular reactive form. for this, we will create new custom validator for not contain space on input field. So at first we have to create file for custom validation like NameValidator.

Step 1:

In file NameValidator.ts

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

Step 2:

In file app.component.ts

import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { NameValidator  } from '../app/country'; 
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  public myForm: FormGroup;
  
  constructor(private formBuilder: FormBuilder) {
    this.myForm = formBuilder.group({
      name: ['', [Validators.required, Validators.minLength(3), NameValidator.cannotContainSpace]]
    })
  }
   
  onSubmit(){
    console.log(this.myForm.value);
  }
}

Step 3:

In file app.component.html

<div class="container mt-5">
    <h4>Whitespace Form Validation</h4>
    <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="myForm.get('name')?.touched && myForm.get('name')?.invalid" class="alert alert-danger">
                <div *ngIf="myForm.get('name')?.errors?.['required']">Please provide name</div>
                <div *ngIf="myForm.get('name')?.errors?.['minlength']">Name must be 4 characters</div>
                <div *ngIf="myForm.get('name')?.errors?.['cannotContainSpace']">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>

Step 4:

npm start in terminal

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories