【问题标题】:Conditional Match field validator in Reactive Form反应形式的条件匹配字段验证器
【发布时间】:2018-01-17 20:15:48
【问题描述】:

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

如果 LoginType 不是 UserName Password,我有条件代码会隐藏密码字段

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 添加到我的代码中?

【问题讨论】:

    标签: angular angular5 angular-reactive-forms


    【解决方案1】:

    我要做的是,与其麻烦地有条件地设置验证器,不如有条件地应用表单组,在已经设置了验证器的情况下,您只需根据条件删除/添加表单组。

    这是一个示例:

    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(在你的情况下为loginType)的 valueChanges 并删除/添加 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

    【讨论】:

      猜你喜欢
      • 2018-03-21
      • 2022-01-26
      • 2021-01-14
      • 2022-11-03
      • 1970-01-01
      • 2019-03-22
      • 2018-12-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多