代码之家  ›  专栏  ›  技术社区  ›  Dreamer

用Angular 6对所有字段应用一个验证规则的简单方法吗

  •  -1
  • Dreamer  · 技术社区  · 7 年前

    我可以计算出regex模式,但只是想知道对所有字段执行一个验证器的简单方法。

    1 回复  |  直到 7 年前
        1
  •  1
  •   HDJEMAI    7 年前

    有一个简单的解决方案,例如只使用一个异步验证器。

    然后对它们应用验证器。

    例子:

    this.mySubForm = this.fb.group({
        field1: ['', [Validators.required]],
        field2: ['', [Validators.required]],
        ...
        field20: ['', [Validators.required]]
    }, this.validatorAllFields.bind(this)
    
       });
    

    并按如下方式定义异步验证器:

    validatorAllFields(control: FormGroup): any {
      if (control) {
          if(control.value.field1 don't contain special char … &&
             control.value.field2 don't contain special char … &&
             …
             control.value.field20 don't contain special char &&)
             //validation is ok in this case
             return null;
          else
             //validation fails here...
             return {'formInvalid': 'true'}
      } else {
          return null;
        }
      }
    

    你可以这样做,而不需要任何额外的包,它将工作。

    你可以用 formGroupName 对于子表单,甚至可以避免使用子表单。

    推荐文章