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

前端 未结 4 1582
不知归路
不知归路 2021-01-03 09:02

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

相关标签:
4条回答
  • 2021-01-03 09:38

    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

    0 讨论(0)
  • 2021-01-03 09:50

    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 };
      }
    
    0 讨论(0)
  • 2021-01-03 09:57

    Use the following:

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

    DEMO

    0 讨论(0)
  • 2021-01-03 09:58

    hey i know i am very late in party but i have also faced same issue on which i have tired 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

    I hope this will help somebody in future.

    0 讨论(0)
提交回复
热议问题