10

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

3
  • 1
    Guys, if you wanna downvote and not explain why go on youtube plz Commented Mar 24, 2017 at 8: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 of the whole problem. Commented Oct 2, 2017 at 7: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 Commented Oct 2, 2017 at 18:27

5 Answers 5

15

Use the following:

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

DEMO

Sign up to request clarification or add additional context in comments.

1 Comment

For me it only worked when I used lower case "S" i.e ---> Validators.pattern(/^\s*$/)
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 };
  }

3 Comments

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.
@PoonamThote check the Update please
Update 2 works perfectly to use in validation service. Thanks
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

2 Comments

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
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.
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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.