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

前端 未结 4 1614
不知归路
不知归路 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: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 };
      }
    

提交回复
热议问题