如何在formBuilder Angular中添加条件验证器

时间:2019-05-04 17:40:16

标签: angular forms angular-reactive-forms

在Angular 7.x中,使用formBuilder和ReactiveForms,我试图将验证器放到基于用户角色的表单中。因此,当用户使用不同的role时,要求他/她输入一个字段。我将此用户存储在类中存储的变量中。

我不想将验证程序放在valueChange的订阅上,而是放在初始版本上。我该怎么做?在一些代码下面。

 buildForm(): void {
    this.accountForm = this.formBuilder.group({
      firstName: [this.user.firstName, Validators.required],
      initials: [this.user.initials, Validators.required],
      lastNamePrefix: [this.user.lastNamePrefix],
      lastName: [this.user.lastName, Validators.required],
      cellPhoneNumber: [this.user.cellPhoneNumber], <-- make this one required if the role of the user is x
      ]),
    });
  }

1 个答案:

答案 0 :(得分:1)

假设设置了验证器后,用户的角色不会改变,则可以采用以下方法:

import {ValidatorFn, Validators} from '@angular/forms';

function createCellPhoneValidator(user: FooUser): ValidatorFn {
  return user.role === x ? Validators.required : Validators.nullValidator;
}

export class FooComponent {
  buildForm(): void {
    this.accountForm = this.formBuilder.group({
      firstName: [this.user.firstName, Validators.required],
      initials: [this.user.initials, Validators.required],
      lastNamePrefix: [this.user.lastNamePrefix],
      lastName: [this.user.lastName, Validators.required],
      cellPhoneNumber: [this.user.cellPhoneNumber, createCellPhoneValidator(this.user)],
    });
  }
}

如果角色可以更改,那么您每次执行验证之前都需要重新评估角色。可以这样做:

import {ValidatorFn, Validators} from '@angular/forms';

export class FooComponent {
  buildForm(): void {
    this.accountForm = this.formBuilder.group({
      firstName: [this.user.firstName, Validators.required],
      initials: [this.user.initials, Validators.required],
      lastNamePrefix: [this.user.lastNamePrefix],
      lastName: [this.user.lastName, Validators.required],
      cellPhoneNumber: [this.user.cellPhoneNumber, this.cellPhoneValidator],
    });
  }

  private readonly cellPhoneValidator: ValidatorFn = c => {
     return this.user.role === "x" ? Validators.required(c) : Validators.nullValidator(c);
   }
}