如何在Angular 7中使用反应形式设置“至少应填写一个字段”验证?

时间:2019-06-26 06:28:30

标签: angular angular7 angular-reactive-forms angular-forms angular-formbuilder

我在角度7中有一个反应形式,其中有三个字段,电子邮件,电话和寻呼机。我的要求是,至少应由用户填写其中之一,否则我们将引发类似“请指定通知之一(电子邮件,SMS或寻呼机)”的错误。

我尝试编写自定义通知,但无法正常工作。您能帮我解决我哪里出问题了。

下面是我的HTML代码:

<form class="form-horizontal" [formGroup]="editorForm">
  <div class="form-group" required>
      <label for="emailAdressInput">Email Addresses</label>
      <input type="text" id="emailAdressInput" formControlName="emailAdresses">
  </div>

<div class="form-group" required>
      <label for="phoneNumberInput">Email Addresses</label>
      <input type="text" id="phoneNumberInput" formControlName="phoneNumber">
  </div>

<div class="form-group" required>
      <label for="pagerNumberInput">Email Addresses</label>
      <input type="text" id="pagerNumberInput" formControlName="pagerNumber">
</div>
</form>

下面是component.ts代码:

this.editorForm = this._formBuilder.group({
          displayLabel: ['', Validators.required],
          emailAdresses: [''],
          phoneNumber: [''],
          notification: this._formBuilder.group({
            pagerNumber: [''],
            phoneNumber: [''],
            emailAdresses: ['']
          }, this.atLeastOneValidator()),
          pagerNumber: [''],
       });

       public atLeastOneValidator = () => {
         return (controlGroup) => {
           let controls = controlGroup.controls;
            if ( controls ) {
                let theOne = Object.keys(controls).find(key=> controls[key].value!=='');
               if ( !theOne ) {
                return {
                    atLeastOneRequired : {
                        text : 'At least one should be selected'
                    }
                }
            }
        }
        return null;
    };
};

3 个答案:

答案 0 :(得分:1)

atLeastOneValue(form: FormGroup): ValidationErrors {
  return Object.keys(form.value).some(key => !!form.value[key]) ? 
    null : 
    { atLeastOneRequired : 'At least one should be selected' };
}

并通过

调用
builder.group({...}, [this.atLeastOneValue]);

答案 1 :(得分:1)

我已经在stackblitz中解决了它:https://stackblitz.com/edit/angular-j3i4yg

strtok

模板:

export class AppComponent {
  name = 'Angular';

  editorForm: FormGroup;
  // _formBuilder: FormBuilder = new FormBuilder();
  constructor(private _formBuilder: FormBuilder) {

    this.editorForm = this._formBuilder.group({
      displayLabel: ['', Validators.required],
      emailAdresses: [''],
      phoneNumber: [''],
      notification: this._formBuilder.group({
        pagerNumber: [''],
        phoneNumber: [''],
        emailAdresses: ['']
      }, { validators: this.atLeastOneValidator }),
      pagerNumber: [''],
    });
  }

  public atLeastOneValidator: ValidatorFn = (control: FormGroup): ValidationErrors | null => {

    let controls = control.controls;
    console.log(controls);
    if (controls) {
      let theOne = Object.keys(controls).findIndex(key => controls[key].value !== '');
      if (theOne === -1) {
        console.log(theOne);
        return {
          atLeastOneRequired: {
            text: 'At least one should be selected'
          }
        }
      }
    };

  }
}

检查并让我知道是否有任何疑问。

答案 2 :(得分:1)

要指示验证者在表单组中使用formBuilder,请添加{validators:yourValidator}

  

group(controlsConfig:{[key:string]:any;},选项:AbstractControlOptions | {[key:string]:any;} = null)

请参见文档AbstractControlOptions

(如果要创建formControl,可以直接添加验证器)

this.editorForm = this._formBuilder.group({
          displayLabel: ['', Validators.required],
          emailAdresses: [''],
          phoneNumber: [''],
          notification: this._formBuilder.group({
            pagerNumber: [''],
            phoneNumber: [''],
            emailAdresses: ['']
          },{ validators:this.atLeastOneValidator()}), //<--THIS
          pagerNumber: [''],
       });
  }

更多,您忘记了.html中的<div formGroupName="notification">

无论如何,我建议不要使用formBuilder,您可以使用表单组和formControl之类的构造函数

  this.editorForm = new FormGroup({
          displayLabel: new FormControl('', Validators.required),
          emailAdresses: new FormControl(''),
          phoneNumber: new FormControl(''),
          notification: new FormGroup({
            pagerNumber: new FormControl(''),
            phoneNumber: new FormControl(''),
            emailAdresses: new FormControl('')
          },this.atLeastOneValidator()), 
          pagerNumber: new FormControl(),
       });
  }