10

I used formBuilder in Angular2 and want to add validation pattern for not to allow "only spaces" in input.

Poonam Thote
  • 367
  • 3
  • 5
  • 12
  • 1
    Guys, if you wanna downvote and not explain why go on youtube plz – theFreedomBanana Mar 24 '17 at 08:01
  • 1
    @theFreedomBanana Isn't that obvious? At OP: What have you tried? Show us some code. Why / how did it fail? Was there an error message? Show us an [example](https://stackoverflow.com/help/mcve) of the whole problem. – TobiMcNamobi Oct 02 '17 at 07:01
  • 1
    @TobiMcNamodi I don't really see the need for code or an example, the title is pretty self-explanatory. And even though, the OP seems fresh new on S.O, probably not aware of all the discipline some of us requires, and downvoting without a comment will not enlight her – theFreedomBanana Oct 02 '17 at 18:27

5 Answers5

15

Use the following:

Validators.pattern(/^\S*$/)

DEMO

AT82
  • 71,416
  • 24
  • 140
  • 167
12

space Not allowed

let nospacePattern = [a-zA-Z0-9]

Update

As per requirement in comment section.

need pattern not to allow only spaces. (space in between words are allowed).but when user enter spaces in input and try to save it then it should not allow to save

Validators.pattern(".*\\S.*[a-zA-z0-9 ]");

Update 2

Better and Cleaner way to use custom validation pattern like below -

controlName: ['', [Validators.required, this.noWhitespaceValidator]],

....
....
noWhitespaceValidator(control: FormControl) {
    const isWhitespace = (control && control.value && control.value.toString() || '').trim().length === 0;
    const isValid = !isWhitespace;
    return isValid ? null : { 'whitespace': true };
  }
Pardeep Jain
  • 84,110
  • 37
  • 165
  • 215
6

try this, it will return false while sapce key press :

@Component({
  selector: 'my-app',
  template: `
    <div>
       <input class="form-control" type="number" formControlName="pinCode" placeholder="Pin Code"
             (keydown.space)="$event.preventDefault()">
    </div>
  `,
  providers: [myService]
})

visit for more Events :

https://developer.mozilla.org/en-US/docs/Web/Events

Rahul Tank
  • 770
  • 1
  • 8
  • 20
  • This will work only for user pressing the space key, if they copy/paste a text with a space in between two words, the field will allow this anyway – Oscar_sgc May 29 '19 at 16:34
  • This won't work if you want to enter a value like e.g. `John Doe`. You can't add the empty space after first name. Also the question says to prevent adding `ONLY` empty space, not preventing adding a space between words. – k.vincent Nov 28 '19 at 08:10
3

I have also faced same issue on which I have tried following code and it works.

As per my requirement, in form comment box should be has min 30 character and that character should be non-space.so to add validation I have used following code. I am using reactive forms. In ts file, add following code

comment:[''[Validators.required,Validators.minLength(30),Validators.pattern(/^((?!\s{2,}).)*$/)]]

Hey this sentence has one space between every word //this will work

Hey this sentence has more than one space between every word //this will throw err

halfer
  • 19,824
  • 17
  • 99
  • 186
sangRam
  • 315
  • 4
  • 17
2

I would suggest using a custom Validator:

export class SharedCustomValidators {
  static spaceOnlyValidator(
    control: AbstractControl
  ): { [key: string]: any } | null {
    const isSpace = /^\s+$/.test(control.value);
    if (control.value && isSpace) {
      return { isOnlyWhiteSpace: true };
    }
    return null;
  }
}

Then to use it:

businessName: [
   '',
   [Validators.required, SharedCustomValidators.spaceOnlyValidator],
],

Explanation

  • The regex /^\s+$/ is used to check if the value is space only
  • If it is space only an error isOnlyWhiteSpace, is returned in the control's errors object

Advantages

  • Reusable
  • Custom error code

Bonus

  • You can add as many validators as you want on that class
James Ikubi
  • 2,552
  • 25
  • 18