【问题标题】:Angular Remove a Specific Form Validator, Not All of them in FormbuilderAngular 删除特定的表单验证器,而不是 Formbuilder 中的所有验证器
【发布时间】:2020-04-27 13:43:55
【问题描述】:

在 Angular Formbuilder 中,如何删除特定验证器? 有

this.form.get('lastName').clearValidators()

但是,这会删除所有验证器,只是想删除“必需”验证器,并保留最小和最大长度。

this.editAddressForm = this.formBuilder.group({
  'firstName': [null, [Validators.maxLength(50)]],
  'lastName': [null, [Validators.required, Validators.maxLength(2), Validators.maxLength(50)]],
  'city': [null, [Validators.required, Validators.maxLength(50)]],
  'zipCode': [null, [Validators.required, Validators.maxLength(50)]]
})

资源:

Angular 4 remove required validator conditionally

【问题讨论】:

    标签: angular typescript angular-reactive-forms angular8


    【解决方案1】:

    我不知道实现此目的的内置方法。

    但是,您可以采用这种方法:

    const validators = [Validators.required, Validators.min(30), Validators.max(100)];
    const fc = new FormControl('', validators)
    
    console.log(fc.valid) // false
    
    const newValidators = validators.filter(v => v !== Validators.required);
    
    fc.setValidators(newValidators);
    fc.updateValueAndValidity();
    
    console.log(fc.valid) // true
    

    【讨论】:

      【解决方案2】:

      我会尝试这样的:

      this.form.get('lastName').setValidators([Validators.maxLength(2), Validators.maxLength(50)]);
      this.form.updateValueAndValidity();
      

      【讨论】:

      • 我有一组验证器,所以需要可重现且可在多种情况下使用的解决方案
      猜你喜欢
      • 2021-03-08
      • 2022-07-26
      • 2020-06-05
      • 2018-07-10
      • 2020-06-16
      • 2018-03-11
      • 1970-01-01
      • 2017-02-05
      • 1970-01-01
      相关资源
      最近更新 更多