Reactive Form中的条件匹配字段验证程序

时间:2018-01-17 08:32:44

标签: angular angular5 angular-reactive-forms

我想在我的被动表单代码上实现一个条件匹配字段验证器,但不确定如何。

如果LoginType不是UserName密码

,我有条件代码隐藏密码字段
public userForm: FormGroup;

ngOnInit() { 
    this.createFormControls();
    this.createForm();
    this.userForm.get('loginType').valueChanges.subscribe(

    (loginType: string) => {
        this.userForm.get('password').setValidators([]);
        this.userForm.get('confirmPassword').setValidators([]);


        if (loginType== 'UsernamePassword') {   this.userForm.get('password').setValidators([Validators.required, Validators.minLength(8), Validators.pattern(/^.*(?=.{8,30})(?=.*[a-z])(?=.*[A-Z])(?=.*[\d])(?=.*[\d])(?=.*[\W]).*$/)]);
                this.userForm.get('confirmPassword').setValidators([Validators.required, Validators.minLength(8), Validators.pattern(/^.*(?=.{8,30})(?=.*[a-z])(?=.*[A-Z])(?=.*[\d])(?=.*[\d])(?=.*[\W]).*$/)]);
        }

        this.userForm.get('password').updateValueAndValidity();
        this.userForm.get('confirmPassword').updateValueAndValidity();

    }

    )
}

上述作品

我想实现一个MatchValidator,我发现这些示例都使用类似于this的方法

 this.form = fb.group({
     password: ['', Validators.required],
     confirmPassword: ['', Validators.required]
    }, {
      validator: PasswordValidation.MatchPassword // your validation method
    })

但是我不知道在我的特定代码中有条件地说,因为我使用this.userForm或带有this.userForm.get('controlName')的控件引用表单

当我使用带有valueChanges.subscribe和updateValueAndValidity的条件逻辑时,如何在我的代码中添加MatchFieldValidator?

1 个答案:

答案 0 :(得分:0)

我要做的是,而不是有条件地设置验证器的麻烦,而是有条件地应用formgroup,其中验证器已经设置,你只需根据条件删除/添加formgroup。

以下是一个示例:

constructor(private fb: FormBuilder) {
  // build nested formgroups that you will conditionally apply / remove
  this.group1 = this.fb.group({
    password: ['', [....]],
    confirm_password: ['', [....]]
  }, { validator: PasswordValidation.MatchPassword })

  this.group2 = this.fb.group({
    some_other: ['', [...]],
  })
  // your parent form, with group1 set initially
  this.myForm = this.fb.group({
    toggler: [false], // this one toggles groups
    group1: this.group1
  })
}

然后,您只需听取toggler的valueChanges(在您的情况下为loginType)并删除/添加formGroup。这里toggler是一个复选框,所以......

this.myForm.controls.toggler.valueChanges
  .subscribe(bool => {
    if (bool) {
      this.myForm.removeControl('group1');
      this.myForm.setControl('group2', this.group2)
    } else {
      this.myForm.removeControl('group2');
      this.myForm.setControl('group1', this.group1)
    }
    this.myForm.updateValueAndValidity();
  });

现在您有条件地应用这些组。

这是一个

StackBlitz