跳轉到

表單送出前驗證欄位

表單送出前的欄位驗證分為兩種,一是前端驗證,另一種是透過 API 等待結果決定是否可以送出。

設定前端驗證

可以透過「Angular」原本就支援的基本驗證與自訂欄位的驗證函式,設定在欄位初始化之後。

表單按下送出時,前端會先檢查parentForm是否通過驗證,而selfControl屬於parentForm的其中一個 control,所以當selfControl驗證不過的時候,會直接阻擋parentForm驗證。

advance-field.write.component.ts
initForm() {
  console.log('initForm', this.exProps);
  this.form = this.fb.group({
    'empNo': [this.value?.empNo ?? '', Validators.required],
    'mobile': [this.value?.mobile ?? '', [createMobileValidator(), Validators.minLength(10)]],
    'applyDate': [this.value?.applyDate, [Validators.required, createApplyDateValidator(this.exProps.checkDays)]]
  });

  // 表單送出時的前端驗證
  if (this.selfControl) {
    // 在此便可設定自己的驗證器
    this.selfControl.setValidators(validateSelf(this.form));
    this.selfControl.updateValueAndValidity();
  }
}    

設定後端驗證

表單本身的設計驗證分成兩段,確定前端驗證都通過後,才會在下個階段前進行後端 API 驗證。

在欄位填寫模式內實作 checkBeforeSubmit(),回傳結果Promise<boolean>resolve(true)表示通過驗證,resolve(false)表示未通過驗證,回傳false會阻擋表單送出。

advance-field.write.component.ts
/** 表單submit前要做的檢查 */
checkBeforeSubmit(): Promise<boolean> {
  return new Promise(resolve => {
    const value = this.form.value;
    console.log(value);
    // 呼叫 API 之前要設定 serverUrl 為外掛欄未站台位址
    this.empService.serverUrl = this.pluginSetting?.entryHost;
    // 呼叫 API 檢查 emp 是否有效
    this.empService.getValidEmpNumber().subscribe(res => {
      if (res?.length ?? 0 > 0) {
        const ary = res;
        if (ary.indexOf(this.empNo) < 0) {
          resolve(false);
        } else resolve(true);
      } else resolve(false);
    });
  });
}