Week 05 · Day 05 — 表單驗證基礎

學習目標

  • 掌握內建驗證器(Required / MinLength / Email 等)
  • 理解錯誤物件的結構 { 錯誤名稱: 資訊 }
  • 判別不同錯誤類型顯示訊息

重點

常用內建驗證器 | 驗證器 | 用途 | |--------|------| | Validators.required | 必填 | | Validators.minLength(n) | 最少字數 | | Validators.maxLength(n) | 最多字數 | | Validators.email | 合法 email | | Validators.pattern(regex) | 符合規則 | | Validators.min(n) / max(n) | 數值範圍 |

錯誤物件結構

// 當驗證失敗,控制項的 .errors 會長這樣:
{
  required: true,
  minlength: { requiredLength: 6, actualLength: 3 }
}
- 用 control.errors 判斷是哪種錯誤

顯示不同錯誤

<div *ngIf="name?.touched && name?.invalid">
  <p *ngIf="name?.hasError('required')">Name 是必填</p>
  <p *ngIf="name?.hasError('minlength')">Name 最少 2 字</p>
</div>
或使用「錯誤有值才顯示」的寫法:
<div *ngIf="name?.invalid && name?.touched">{{ getErrorMessage(name) }}</div>
getErrorMessage(c: AbstractControl | null): string {
  if (c?.hasError('required')) return '必填';
  if (c?.hasError('minlength')) return `最少 ${c.errors?.['minlength']?.requiredLength} 字`;
  return '';
}

實作

  1. name 同時加 requiredminLength(2)
  2. hasError 分別顯示「必填」與「字數不足」
  3. 輸入不同情況確認錯誤訊息切換

作業

  • 在表單中應用至少 3 種內建驗證器
  • hasError('required') 判斷必填
  • 說出 .errors 物件的結構