Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add Validation pattern not to allow only space in input Angular2?

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

like image 412
Poonam Thote Avatar asked Mar 24 '17 07:03

Poonam Thote


People also ask

Is it possible to define validators in form builder?

FormBuilder allows us to explicitly declare forms in our components. This allows us to also explicitly list each form control's validators.

What are custom validators?

Building a custom validator In it's simplest form, a validator is really just a function that takes a Control and returns either null when it's valid, or and error object if it's not.


2 Answers

Use the following:

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

DEMO

like image 73
AT82 Avatar answered Sep 20 '22 05:09

AT82


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 };
  }
like image 30
Pardeep Jain Avatar answered Sep 19 '22 05:09

Pardeep Jain