在Angular反应形式中向FormArray添加自定义验证器

时间:2018-09-11 11:30:59

标签: angular angular-reactive-forms

我有这样的反应形式

this.form = this.fb.group({
      items: this.fb.array(
        [
          this.fb.group({
            net_amount: [
              null,
              Validators.compose([
                Validators.required,
                Validators.pattern('^[0-9]+(.?[0-9]+)?$'),
                isValidNumericValue
              ])
            ],
          })
        ],
        Validators.required
      ),
      substances: this.initAdditives(),
      net_total: [
        this.currentProduct.net_total || null,
        [
          Validators.required,
          Validators.pattern('^[0-9]+(.?[0-9]+)?$'),
          isValidNumericValue
        ]
      ]
    });

isValidNumericValue是一个自定义验证器,它检查数字是否大于零。问题是验证器在FormArray外部但不在内部。

  export function isValidNumericValue(AC: AbstractControl) {
    if (AC.value <= 0) {
      return { numericError: true };
    }
    return null;
  }

1 个答案:

答案 0 :(得分:1)

我认为您的问题是,因为您要将验证器应用于fb.group,因此您应该这样做:

this.fb.group({
      net_amount: [null, [Validators.required, Validators.pattern('^[0-9]+(.?[0-9]+)?$')]
    ],
  }, { validator: isValidNumericValue })

我将在此处向您发布一个同时包含“组”和“单人”验证的表单:

首先,您需要创建验证规则:

function emailMatch(c: AbstractControl): {[key: string]: boolean} | null {
    let email = c.get('email');
    let confirmEmail = c.get('confirmEmail');

    if (email.value === confirmEmail.value) {
        return null;
    }
    return { 'match': true };
 }

此验证我将用于产品的星级评定,例如:

function MyRangeFunction (min: number, max: number): ValidatorFn {
    return  (c: AbstractControl): {[key: string]: boolean} | null => {
        if (ifYouGotError) {
            return { 'range': true };
        };
        return null;
    };
}

现在我的表单是这样:

this.myForm = this.fb.group({
            emailGroup: this.fb.group({
                email: ['', [Validators.required, Validators.pattern('[a-z0-9._%+-]+@[a-z0-9.-]+')]],
                confirmEmail: ['', Validators.required],
            }, {validator: emailMatch}),

            rating: ['', MyRangeFunction (1, 5)],
        });

我认为在这里您已经了解了验证的全部内容!