簡體   English   中英

角度驗證一對表單字段為空或均填充

[英]angular validate that a pair of form fields are empty or both are filled

我創建了一個包含4到5個字段的學生表格。 對於聯系電話,我有2個字段,國家/地區代碼和電話號碼。 如果用戶僅輸入兩個字段之一(即輸入了國家/地區代碼,但電話號碼不是,反之亦然),我想拋出一個錯誤。 但是,如果兩個字段都保留為空,則由於兩個都是非強制性字段,因此它是有效的。 我不知道該如何實現。 請幫忙。 提前致謝。

這是我的模板:

<mat-form-field >
<input matInput type="number"   formControlName="countryCode" placeholder="Country Code(+)" name="countryCode" class="form-control" id="countryCode">
</mat-form-field>
<mat-form-field >
<input matInput type="number" formControlName="phnNumber" placeholder="Phone Number" name="phnNumber" class="form-control" id="phnNumber">
</mat-form-field>

我的表格組:

this.addForm = this.formBuilder.group({

      studentName: ['', Validators.required],
      phnNumber: new FormControl(''),
      countryCode: new FormControl(''),
    });

您可以創建一個自定義驗證器,將其作為整體而不是單個控件放置在FormGroup上。 您對FormBuilder呼叫變為:

this.addForm = this.formBuilder.group({

      studentName: ['', Validators.required],
      phnNumber: new FormControl(''),
      countryCode: new FormControl(''),
    }, { validators: myFormValidator });

然后您創建一個驗證器(在同一文件或其他位置並導出):

export const myFormValidator: ValidatorFn = (control: FormGroup): ValidationErrors | null => {
  const phnNumber = control.get('phnNumber').value;
  const countryCode = control.get('countryCode').value;

  if (phnNumber && !countryCode || countryCode && !phnNumber) {
    return { 'phoneNumberError': true };
  } else {
    return null;
  }
};

這樣,自定義驗證器就可以從整個組中獲取所需信息,而不是需要單獨驗證控件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM