105

I would like to avoid white spaces/empty spaces in my angular 2 form? Is it possible? How can this be done?

DeadlyChambers
  • 5,217
  • 4
  • 44
  • 61
Eusthace
  • 3,601
  • 7
  • 34
  • 41
  • you just have to trim the field as two way data binding. You can consider a custom pipe too – afmeva Aug 30 '16 at 22:23
  • Maybe this article can help you http://blog.angular-university.io/introduction-to-angular-2-forms-template-driven-vs-model-driven/ – Bruno João Sep 02 '16 at 19:21

23 Answers23

247

You can create a custom validator to handle this.

new FormControl(field.fieldValue || '', [Validators.required, this.noWhitespaceValidator])

Add noWhitespaceValidator method to your component

public noWhitespaceValidator(control: FormControl) {
    return (control.value || '').trim().length? null : { 'whitespace': true };       
}

and in the HTML

<div *ngIf="yourForm.hasError('whitespace')">Please enter valid data</div>
masum7
  • 822
  • 6
  • 17
Praveen M P
  • 11,314
  • 7
  • 34
  • 41
  • 18
    I think I prefer this approach because its makes the rule reusable. Even being mine response marked as the correct one. – Bruno João Mar 31 '17 at 12:08
  • 11
    To make it reusable in other components: replace 'public' with 'export function', then put it into a file (eg: src/app/utils/no-whitespace.validator.rs), and add the line to import FormControl. Now you can import this validator into any control you like :) – rmcsharry Sep 27 '17 at 18:25
  • @rmcsharry you are absolutely right.. that is how we need to write and maintain the code. – Praveen M P Sep 28 '17 at 07:27
  • How could the `noWhitespaceValidator` be modified to allow for `strictNullChecks: true` to be set in `tsconfig.json`? – Ryan Buening Jul 30 '18 at 14:22
  • this indeed is a better, clean , reusable and explicit approach. Should have been the accepted answer @Eusthace – Saurabh Tiwari Sep 11 '18 at 13:44
  • How can I make this for password field – Md. Parvez Alam Sep 14 '18 at 06:46
  • 5
    //above answer is perfect only suggesting one check to avoid collision with angular required validator. public noWhitespaceValidator(control: FormControl) { const isWhitespace = control.value.length > 0 && (control.value).trim().length === 0; const isValid = !isWhitespace; return isValid ? null : { 'whitespace': true }; } – Rahul Talar Dec 17 '18 at 12:30
  • 1
    I found this more convenient and easy to customize. – Tanzeel Aug 22 '20 at 04:52
32

I think a simple and clean solution is to use pattern validation.

The following pattern will allow a string that starts with white spaces and will not allow a string containing only white spaces:

/^(\s+\S+\s*)*(?!\s).*$/

It can be set when adding the validators for the corresponding control of the form group:

const form = this.formBuilder.group({
            name: ['', [
                Validators.required,
                Validators.pattern(/^(\s+\S+\s*)*(?!\s).*$/)
            ]]
        });
18

Maybe this article can help you http://blog.angular-university.io/introduction-to-angular-2-forms-template-driven-vs-model-driven/

In this approach, you have to use FormControl then watch for value changes and then apply your mask to the value. An example should be:

...
form: FormGroup;
...


ngOnInit(){
    this.form.valueChanges
            .map((value) => {
                // Here you can manipulate your value
                value.firstName = value.firstName.trim();
                return value;
            })
            .filter((value) => this.form.valid)
            .subscribe((value) => {
               console.log("Model Driven Form valid value: vm = ",JSON.stringify(value));
            });

}
Bruno João
  • 5,105
  • 2
  • 21
  • 26
14

Prevent user to enter space in textbox in Angular 6

<input type="text" (keydown.space)="$event.preventDefault();" required />
Nick
  • 138,499
  • 22
  • 57
  • 95
shehzad lakhani
  • 495
  • 5
  • 14
  • 18
    You can still paste spaces, or use Alt+0160. – Christian Jan 22 '19 at 09:15
  • Just for anyone else who notices pasting still works, you can use a custom directive to disable pasting. See https://stackoverflow.com/questions/47384952/directive-to-disable-cut-copy-and-paste-function-for-textbox-using-angular2 – Nicky Nov 13 '19 at 21:21
  • 9
    @Nicky you can, but what if a user wants to paste something (legal)? Disabling pasting is making usability worse. – Daniels Šatcs Jan 25 '20 at 18:26
  • @DanielShatz you can just call change event inline function for that. like (change)="yourvalue = yourvalue.trim()" in input element. – Shekhar Patel Oct 05 '20 at 12:44
  • The question was to prevent whitespace/empty spaces. This prevents any space. What if I want a space between two words? – Abhishek Tewari Jan 06 '22 at 17:21
11
    export function noWhitespaceValidator(control: FormControl) {
       const isSpace = (control.value || '').match(/\s/g);
       return isSpace ? {'whitespace': true} : null;
}

to use

 password: ['', [Validators.required, noWhitespaceValidator]]

In template/html

<span *ngIf="newWpForm.get('password').hasError('whitespace')">
    password cannot contain whitespace
</span>
Aklesh Singh
  • 917
  • 10
  • 12
  • 1
    Best and standard approach to validate whitespace .. good thing is we can use this validator across form groups – Surya Prakash Tumma Aug 26 '20 at 17:53
  • For those users copy/pasting this answer into their projects: please allow whitespace in your passwords. There is nothing wrong with a space in a password. – SurfMan Nov 07 '22 at 13:26
10

If you are using Angular Reactive Forms you can create a file with a function - a validator. This will not allow only spaces to be entered.

import { AbstractControl } from '@angular/forms';
export function removeSpaces(control: AbstractControl) {
  if (control && control.value && !control.value.replace(/\s/g, '').length) {
    control.setValue('');
  }
  return null;
}

and then in your component typescript file use the validator like this for example.

this.formGroup = this.fb.group({
  name: [null, [Validators.required, removeSpaces]]
});
Dilshan Liyanage
  • 4,440
  • 2
  • 31
  • 33
  • 2
    I know this answer is over a year old, but I just tried it. When I created my form control, i defaulted it to '' instead of null and this caused an infinite loop some how. I changed my default to null and continued testing. If I went into the field, typed a few characters and then deleted them, it said the field was valid even though it should have fail required validation. It's a shame. I really liked this solution. – fizch Jan 05 '20 at 05:05
  • 2
    I was trying this approach in my code, but it was not throwing required error even control had empty value as ''. so returned in the function {required : true} below control.setvalue(''); and it worked like a charm. Thanks. – Nitin Shekhar Jul 28 '20 at 08:16
10

An alternative would be using the Angular pattern validator and matching on any non-whitespace character.

const nonWhitespaceRegExp: RegExp = new RegExp("\\S");

this.formGroup = this.fb.group({
  name: [null, [Validators.required, Validators.pattern(nonWhiteSpaceRegExp)]]
});
guest
  • 101
  • 1
  • 2
6

What I did was created a validator that did the samething as angular for minLength except I added the trim()

import { Injectable } from '@angular/core';
import { AbstractControl, ValidatorFn, Validators } from '@angular/forms';


@Injectable()
export class ValidatorHelper {
    ///This is the guts of Angulars minLength, added a trim for the validation
    static minLength(minLength: number): ValidatorFn {
        return (control: AbstractControl): { [key: string]: any } => {
            if (ValidatorHelper.isPresent(Validators.required(control))) {
                return null;
            }
             const v: string = control.value ? control.value : '';
            return v.trim().length < minLength ?
                { 'minlength': { 'requiredLength': minLength, 'actualLength': v.trim().length } } :
                null;
        };
    }

    static isPresent(obj: any): boolean {
        return obj !== undefined && obj !== null;
    }
}

I then in my app.component.ts overrode the minLength function provided by angular.

import { Component, OnInit } from '@angular/core';    
import { ValidatorHelper } from 'app/common/components/validators/validator-helper';
import { Validators } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {  
  constructor() { }

  ngOnInit(): void {       
    Validators.minLength = ValidatorHelper.minLength;
  }
}

Now everywhere angular's minLength built in validator is used, it will use the minLength that you have created in the helper.

Validators.compose([
      Validators.minLength(2)         
    ]);
DeadlyChambers
  • 5,217
  • 4
  • 44
  • 61
5

Following directive could be used with Reactive-Forms to trim all form fields so standart Validators.required work fine:

@Directive({
  selector: '[formControl], [formControlName]',
})
export class TrimFormFieldsDirective {
  @Input() type: string;

  constructor(@Optional() private formControlDir: FormControlDirective, 
              @Optional() private formControlName: FormControlName) {}

  @HostListener('blur')
  @HostListener('keydown.enter')
  trimValue() {
    const control = this.formControlDir?.control || this.formControlName?.control;
    if (typeof control.value === 'string' && this.type !== 'password') {
      control.setValue(control.value.trim());
    }
  }
}
Vilmantas Baranauskas
  • 6,596
  • 3
  • 38
  • 50
  • 1
    This solution can be used for entire application, if you are using reactive forms. Best solution. – Pramod Kumar Sharma Sep 30 '20 at 08:59
  • https://github.com/anein/angular2-trim-directive is a simple solution which works out of the box – Taha Attari Feb 24 '22 at 21:02
  • Solution works fine with Angular v13.3. Just a note that following import statements will be needed: `import { Directive, HostListener, Input, Optional } from '@angular/core';` `import { FormControlDirective, FormControlName } from '@angular/forms';` – Ali Celebi Aug 23 '22 at 14:31
  • 1
    Works great on Angular v14... However, on a username field, `control.setValue` does not fully update the control resulting in the Chrome autofill save password prompt still including the spaces. Using `control.patchValue` instead corrects the issue. And for all of you newbies out there, don't forget to import this directive into your global app or shared module. – xJSx Jun 08 '23 at 22:24
4

This is a slightly different answer to one below that worked for me:

public static validate(control: FormControl): { whitespace: boolean } {
    const valueNoWhiteSpace = control.value.trim();
    const isValid = valueNoWhiteSpace === control.value;
    return isValid ? null : { whitespace: true };
}
Christopher Grigg
  • 2,238
  • 27
  • 33
3

To avoid the form submition, just use required attr in the input fields.

<input type="text" required>

Or, after submit

When the form is submited, you can use str.trim() to remove white spaces form start and end of an string. I did a submit function to show you:

submitFunction(formData){

    if(!formData.foo){
        // launch an alert to say the user the field cannot be empty
        return false;
    }
    else
    {
        formData.foo = formData.foo.trim(); // removes white 
        // do your logic here
        return true;
    }

}
Bruno João
  • 5,105
  • 2
  • 21
  • 26
  • Thank you for your help, but what I need is to avoid the user to just add white spaces and save the form. I believe is possible to validate it in some way. What do you think? – Eusthace Aug 30 '16 at 21:27
  • I have not used input mask with angular 2 form yet. If i do, I'll help you. But now I can't. Try to search for masked input for angular 2 ;) – Bruno João Aug 30 '16 at 22:05
  • Thank you! I'll try to find it. – Eusthace Aug 30 '16 at 22:10
3

To automatically remove all spaces from input field you need to create custom validator.

removeSpaces(c: FormControl) {
  if (c && c.value) {
    let removedSpaces = c.value.split(' ').join('');
    c.value !== removedSpaces && c.setValue(removedSpaces);
  }
  return null;
}

It works with entered and pasted text.

c97
  • 575
  • 4
  • 10
  • I found this solution to be the most portable and less invasive. Using the reactive forms own validation system. It works in every case and can be used around all the the app. Good Job! +1 – Francisco J Sucre G Apr 26 '20 at 18:46
  • Why not just use .trim() instead of .spilit(' ').join('')? – Crystal May 20 '20 at 20:56
  • @Crystal `.trim` removes whitespace at the beginning and end of the string whereas `split`/`join` removes all spaces (and only spaces, not all whitespace eg, tab, newline) anywhere in the string. – Doug Domeny Jan 22 '21 at 19:49
3

I had a requirement where in the Firstname and Lastname are user inputs which were required fields and user should not be able to hit space as the first character.

Import AbstractControl from node_modules.

import { AbstractControl } from '@angular/forms';

check if the first character is space If yes then blank the value and return required: true. If no return null

export function spaceValidator(control: AbstractControl) {
if (control && control.value && !control.value.replace(/\s/g, '').length) {
    control.setValue('');
    console.log(control.value);
    return { required: true }
}
else {
    return null;
}
}

the above code will trigger an error if the first character is space and will not allow space to be the first character.

And in form builder group declare

this.paInfoForm = this.formBuilder.group({
        paFirstName: ['', [Validators.required, spaceValidator]],
        paLastName: ['', [Validators.required, spaceValidator]]
})
Arun
  • 31
  • 2
3

To validate white space in starting in an input you can just call change event and do inline function for that.

<input type="text" class="form-control"                     
            placeholder="First Name without white space in starting"
            name="firstName"
            #firstName="ngModel"
            [(ngModel)]="user.FirstName"
            (change) ="user.FirstName = user.FirstName.trim()"
            required/>
Shekhar Patel
  • 641
  • 10
  • 20
3

If you are using reactive forms in Angular 2+, you can remove leading and trailing spaces with the help of (blur)

app.html

<input(blur)="trimLeadingAndTrailingSpaces(myForm.controls['firstName'])" formControlName="firstName" />

app.ts

public trimLeadingAndTrailingSpaces(formControl: AbstractControl) {
    if (formControl && formControl.value && typeof formControl.value === 'string') {
        formControl.setValue(formControl.value.trim());
    }
}
2

In your app.component.html

<form [formGroup]="signupForm">

           <input  type="text" name="name" [formControl]="signupForm.controls['name']"
              placeholder="First Name"
              required
            />
     <small
            *ngIf="signupForm.controls['name'].hasError('pattern')"
            class="form-error-msg"
            >First Name without space</small>

    </form>

In your app.componen.ts file

import { Validators, FormGroup, FormControl } from "@angular/forms";
signupForm: FormGroup;
ngOnInit(){
this.signupForm = new FormGroup({
  name: new FormControl("", [
    Validators.required,
    Validators.pattern("^[a-zA-Z]+$"),
    Validators.minLength(3)
  ])
})
Tabish Zaman
  • 227
  • 3
  • 4
0

After lots of trial i found [a-zA-Z\\s]* for Alphanumeric with white space

Example:

New York

New Delhi

md-5h04I3
  • 214
  • 2
  • 12
0

i have used form valueChanges function to prevent white spaces. every time it will trim all the fields after that required validation will work for blank string.

Like here:-

this.anyForm.valueChanges.subscribe(data => {
   for (var key in data) {
        if (data[key].trim() == "") {
          this.f[key].setValue("", { emitEvent: false });
        }
      }
    }

Edited --

if you work with any number/integer in you form control in that case trim function will not work directly use like :

this.anyForm.valueChanges.subscribe(data => {
  for (var key in data) {
        if (data[key] && data[key].toString().trim() == "") {
          this.f[key].setValue("", { emitEvent: false });
        }
      }  
  }
paras shah
  • 861
  • 2
  • 9
  • 23
0

In hello.component.html

<input [formControl]="name" />
<div *ngIf="name.hasError('trimError')" > {{ name.errors.trimError.value }} </div>

In hello.component.ts

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

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

export class AppComponent {
  control = new FormControl('', trimValidator);
}

Example Code

0
export function NoWhitespaceValidator(): ValidatorFn {
    return (control: AbstractControl): any => {
        window.setTimeout(() => {
            if (control.value && control.value != '') {
                let trimedvalue = control.value.replace(/\s/g, '');
                control.setValue(trimedvalue);
            }
        }, 10);
    };
}


username: ['', Validators.compose([Validators.required, NoWhitespaceValidator()])],
0

I am late to the party, but I found most answers not fully functional for my use case. I am using regular expression matching, which detects UTF 8 Whitespace correctly (.trim() does not). Additionally I added a null value check. Code is typescript but should be easy to convert to javascript.

notOnlyWhitespaceValidator(control: AbstractControl) {
    const isWhitespace = control.value && control.value.length > 0 && (control.value as string).match(/[^-\s]/) === null;
    const isValid = !isWhitespace;
    return isValid ? null : { 'only-whitespace': true };
  }

Here is a test suite (jest)

  describe('notOnlyWhitespaceValidator', () => {
    it('should not trigger on missing value', () => {
      expect(CustomValidators.notOnlyWhitespaceValidator(new FormControl(''))).toEqual(null);
      expect(CustomValidators.notOnlyWhitespaceValidator(new FormControl())).toEqual(null);
    });

    it('should trigger on only whitespace', () => {
      expect(CustomValidators.notOnlyWhitespaceValidator(new FormControl(' '))).toEqual({ 'only-whitespace': true });
      expect(CustomValidators.notOnlyWhitespaceValidator(new FormControl('\n'))).toEqual({ 'only-whitespace': true });
      // check utf 8 zero with space
      const utf8Space = '\ufeff';
      expect(CustomValidators.notOnlyWhitespaceValidator(new FormControl(utf8Space))).toEqual({
        'only-whitespace': true,
      });
    });

    it('should not trigger on valid input', () => {
      expect(CustomValidators.notOnlyWhitespaceValidator(new FormControl(' Whatever is valid '))).toEqual(null);
      expect(CustomValidators.notOnlyWhitespaceValidator(new FormControl('!'))).toEqual(null);
    });
  });
Paul Weber
  • 6,518
  • 3
  • 43
  • 52
0

you can simply add a pattern validator

Validators.pattern('[\\S]{1,}[\\S\\s]*|[\\s]*[\\S]{1,}[\\S\\s]*')

this will provide a check for white space in leading or later section.

0

It is better to create custom validator using Angular code and customise it like this:

export function required(control: AbstractControl): ValidationErrors | null {
  return isEmptyInputValue(control?.value) ? {'required': true} : null;
}

function isEmptyInputValue(value: any): boolean {
  return value == null ||
    (typeof value === 'string' && value.trim().length === 0) ||
    (Array.isArray(value) && value.length === 0);
}

then you can use your own required validator instead of angular one.

Vahid Forghani
  • 343
  • 1
  • 2
  • 14