为FormBuilder包含基于正则表达式的验证器会破坏Angular 5.29中的检查

时间:2018-10-02 05:07:42

标签: angular formbuilder

这是堆叠闪电战:

https://stackblitz.com/edit/ionic-f9kfnm

基本上,如果构造函数中的formBuilder代码看起来像这样(不包括正则表达式模式):

this.signupForm = this.formBuilder.group({
      nickname: ['', Validators.compose([Validators.minLength(3), Validators.maxLength(20), Validators.required])],
      email: ['', Validators.compose([Validators.email, Validators.required])],
      password: ['', Validators.compose([Validators.minLength(3), Validators.maxLength(20), Validators.required])],
      ageTermsAccepted: [false, Validators.pattern('true')],
      policiesAccepted: [false, Validators.pattern('true')]
    });

使用昵称检查的用户体验看起来不错(警告仅在输入值无效时显示并消失。

现在,如果我添加正则表达式验证器:

this.signupForm = this.formBuilder.group({
      nickname: ['', Validators.compose([Validators.pattern('^[a-zA-Z0-9_-]$'),Validators.minLength(3), Validators.maxLength(20), Validators.required])],
      email: ['', Validators.compose([Validators.email, Validators.required])],
      password: ['', Validators.compose([Validators.minLength(3), Validators.maxLength(20), Validators.required])],
      ageTermsAccepted: [false, Validators.pattern('true')],
      policiesAccepted: [false, Validators.pattern('true')]
    });

支票无法正常工作。

是否有一条规则,如果我使用正则表达式,则仅需依赖它,并且不能将其与其他构建验证器(如max char)结合使用?

1 个答案:

答案 0 :(得分:0)

您的正则表达式缺少量词,因此它仅接受单个字符。

'^[a-zA-Z0-9_-]*$'

或者您可以指定字符的最小和最大数目,还可以删除minLengthmaxLength验证程序(除非您想要不同的验证消息):

'^[a-zA-Z0-9_-]{3,20}$'