【问题标题】:Angular Form Validations Required field + optional fieldAngular 表单验证必填字段 + 可选字段
【发布时间】:2022-11-22 19:49:58
【问题描述】:

所以我的问题是。我有一个非常大的表格来填写 200+ 个输入字段,我需要一个字段(标题),但我也想检查他们是否至少填写了一个其他字段。哪一个都无所谓。但是一旦满足该要求,他们就可以提交表格。

【问题讨论】:

    标签: angular forms validation


    【解决方案1】:

    将验证器添加到 FormGroup 以检查所有输入。

    new FormGroup(
      {
        requiredControl: new FormControl(initialValue, [Validators.required]),
        control1: new FormControl(...),
        ...
        control200: new FormControl(...)
      },
      [someValueValidator()]
    )
    
    private someValueValidator() {
      return (controls: AbstractControl) => {
       // check if any non-required control is set then return null, 
       // otherwise return ValidationError
      }
    }
    

    【讨论】:

      【解决方案2】:

      这很简单,请参阅Stackblitz 示例。您只需要为一个字段设置一个验证器,然后检查 onSubmit 所有其他字段值:

        onSubmit(): void {
          let anyOtherControlIsFilled = false;
      
          Object.keys(this.form.controls).forEach((key) => {
            if (!this.form.controls[key].validator) {
              if (
                this.form.controls[key].value !== null &&
                this.form.controls[key].value !== ''
              ) {
                console.log('Passt');
                anyOtherControlIsFilled = true;
              }
            }
          });
      
          if (this.form.valid && anyOtherControlIsFilled) {
            this.submitted = true;
            alert('All ok');
          } else {
            this.submitted = true;
            alert('Error');
            return;
          }
      
          console.log(JSON.stringify(this.form.value, null, 2));
        }
      

      问候,弗洛

      【讨论】:

        猜你喜欢
        • 2020-02-27
        • 2017-09-15
        • 2017-06-24
        • 1970-01-01
        • 1970-01-01
        • 2017-02-07
        • 1970-01-01
        • 1970-01-01
        • 2012-05-23
        相关资源
        最近更新 更多