3

I'm trying to validate a name field with not allowing spaces in the beginning, also tried this ( Angular Form Input block (space) REGEX ), but that doesn't allow spaces at all.

I have something like this:

<mat-error *ngIf="createEditForm.controls['nameCtrl'].hasError('required')">
    Your Name
</mat-error>

Also tried this ( How to validate white spaces/empty spaces? [Angular 2] ), but that allows the field to start with the space, just doesn't allow a empty space with not chars.

Felipe Avelar
  • 53
  • 2
  • 7

4 Answers4

3

You can create a custom validator :

export function whitespaceValidator(form: FormCntrol): ValidationErrors {
    return form.value.startsWith(" ") ? {whitespace: true} : null;
  }
}

Add it into your form declaration :

createEditForm: FormGroup = new FormGroup({
  nameCtrl: new FormControl('', whitespaceValidator)
})

And change your html to :

<mat-error *ngIf="createEditForm.controls['nameCtrl'].hasError('whitespace')">
    Your Name
</mat-error>
Gérôme Grignon
  • 3,859
  • 1
  • 6
  • 18
1

I've added a trim validator as @AlfMoh said.

import { Component } from '@angular/core';
import { ValidatorFn, FormControl } from '@angular/forms';

const trimValidator: ValidatorFn = (control: FormControl) => {
  if (control.value.startsWith(' ')) {
    return {
      'trimError': { value: 'control has leading whitespace' }
    };
  }
  if (control.value.endsWith(' ')) {
    return {
      'trimError': { value: 'control has trailing whitespace' }
    };
  }

  return null;
};

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  control = new FormControl('', trimValidator);
}

Worked like a charm

Felipe Avelar
  • 53
  • 2
  • 7
1

Even more simple, to avoid white spaces at the beginning and at the end with a number of characters between 3 and 250 :

Validators.pattern("^\\S{1}.{1,248}\\S{1}$")
Tank
  • 11
  • 1
0

Space at start is not allowed we can implement this in couple of steps.

Step: 1 Generate custom validator service as

  ng generate service custom-validator

Step: 2 Filled the service with

 import { Injectable } from '@angular/core';
import { FormControl } from '@angular/forms';

@Injectable({
  providedIn: 'root'
})
export class CustomValidatorService {

  static notAllowedSpaceValidator(control: FormControl) {
    let userInput = control.value;
    if (userInput && userInput.length > 0) {
      if (userInput[0] === " ") {
        return {
          forbiddenSpace: {
            value: userInput,
          },
        };
      }
    } else {
      return null;
    }
  }
}

Step 3 we are almost done, Now we just need to use this validation as

businessesForm: FormGroup; // declaration

 this.businessesForm = fb.group({
      businessName: [
        "",
        [CustomValidatorService.notAllowedSpaceValidator],  // <--- to foucs
      ], 
    });
mabdullahse
  • 3,474
  • 25
  • 23