1

我在 Angular 7 中有一种反应形式,其中包含电子邮件、电话和寻呼机三个字段。我的要求是至少其中一个应该由用户填写,否则我们应该抛出这样的错误“请指定通知之一(电子邮件、短信或寻呼机)。”

我曾尝试编写自定义通知,但它不起作用。你能帮我看看我哪里出错了。

下面是我的 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;
    };
};
4

3 回答 3

3

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

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'
          }
        }
      }
    };

  }
}

模板 :

<form class="form-horizontal" [formGroup]="editorForm">
  <fieldset formGroupName="notification">
  <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>
  </fieldset>

{{editorForm.get('notification')?.errors| json}}
<br>
<br>
<span *ngIf="editorForm.get('notification')?.errors?.atLeastOneRequired"> {{editorForm.get('notification')?.errors?.atLeastOneRequired.text}}</span>

</form>

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

于 2019-06-26T07:20:09.630 回答
2
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]);
于 2019-06-26T07:06:57.890 回答
1

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

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

请参阅文档AbstractControlOptions

(如果要创建formControl,可以直接添加validator)

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

<div formGroupName="notification">此外,您在 .html 中忘记了 a

无论如何,我建议不要使用 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(),
       });
  }
于 2019-06-26T07:21:38.340 回答