如何添加验证模式不允许输入 Angular2 中的空格



我在 Angular2 中使用了 formBuilder,并希望添加验证模式,以便在输入中不允许"只有空格"。

使用以下命令:

Validators.pattern(/^S*$/)

演示

空格 不允许

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

更新

根据评论部分的要求。

需要模式不允许只允许空格。(允许在单词之间留空格(。但是当用户在输入中输入空格并尝试保存它时,它不应该允许保存

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

更新 2

使用自定义验证模式的更好、更简洁的方法,如下所示 -

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 };
  }

试试这个,它会在按下 sapce 键时返回 false:

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

访问更多活动 :

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

我也遇到了同样的问题,我尝试遵循代码并且它可以工作。

根据我的要求,表单注释框中应至少包含 30 个字符,并且应 non-space.so 该字符以添加我使用以下代码的验证。我正在使用反应式形式。在 ts 文件中,添加以下代码

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

Hey this sentence has one space between every word//这将起作用

Hey this sentence has more than one space between every word//这将引发错误

我建议使用自定义验证器:

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;
  }
}

然后使用它:

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

解释

  • 正则表达式/^\s+$/用于检查值是否仅为空格
  • 如果它只是空格,则错误是仅空白,在控件的 errors 对象中返回

优势

  • 可 重用
  • 自定义错误代码

奖金 😉

  • 您可以在该类上添加任意数量的验证器

最新更新