iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 24
0
Modern Web

Angular - 從零開始系列 第 24

Angular - 從零開始 - Day24 - 響應式表單驗證:Reactive Forms

angular

Angular 本身對於 form 表單有強大的支援功能,透過響應式表單,可以自訂要驗證的內容寫在 TS 中,讓 HTML 標籤看起來是比較乾淨的。

有兩個表單,一個是帳號跟密碼,其驗證條件:

  1. 帳號輸入內容為 email 格式。
  2. 密碼輸入有最短長度。

這個頁面會有兩個比較重要的檔案,

  • login.component.html
  • login.component.ts

初始基本架構如下

使用 .inputControl 分別將帳號密碼兩個欄位包起來,因為要共用同一個樣式作為錯誤效果。

<form>
  <div class="inputControl">
    <label>
      <input type="email" />
    </label>
    <label>
      <input type="password" />
    </label>
  </div>
</form>

主要的函式庫

先在 app.module.ts 這隻檔案匯入 FormsModule 跟這次的主角 ReactiveFormsModule

import { FormsModule, ReactiveFormsModule } from "@angular/forms";

加入要驗證的表單內容

在 HTML 中的帳號密碼加入相對應要驗證的內容:

  1. form 標籤使用屬性繫結,變數名稱為 formGroup,其接收 form 的值。
  2. name 改寫成 formControlName
  3. 使用屬性繫結並使用 ngClass,動態的在表單上增加驗證的樣式,當 form 表單要驗證實,就會出現 errors 這個 class,並且執行後方 submitted && f.email.errors 的內容。
  4. p 標籤為驗證的錯誤訊息,並使用 ngIf 做判斷,若錯誤則顯示 DOM 元素。
<form [formGroup]="form" <!-- 帳號 -->
  <div class="inputControl">
    <label>
      <input
        type="email"
        class="formControl"
        formControlName="email"
        [ngClass]="{ 'errors': f.email.errors }"
        placeholder="Account"
      />
    </label>
    <!-- 帳號驗證 -->
    <p class="errors" *ngIf="f.email.errors">
      <span *ngIf="f.email.errors.required">
        <i class="fas fa-exclamation-triangle"></i>請填寫帳號
      </span>
      <span *ngIf="f.email.errors.email">
        <i class="fas fa-exclamation-triangle"></i>信箱格式錯誤
      </span>
    </p>
    <!-- 帳號驗證結束 -->
  </div>

  <!-- 密碼 -->
  <div class="inputControl">
    <label>
      <input
        type="password"
        class="formControl"
        formControlName="password"
        [ngClass]="{ 'errors': f.password.errors }"
        placeholder="Password"
      />
    </label>

    <!-- 密碼驗證-->
    <p class="errors" *ngIf="f.password.errors">
      <span *ngIf="f.password.errors.required">
        <i class="fas fa-exclamation-triangle"></i>請填寫密碼
      </span>
      <span *ngIf="f.password.errors.minlength">請輸入超過6位數密碼</span>
    </p>
    <!-- 密碼驗證結束 -->
  </div>
</form>

使用內建的表單驗證器

Angular 本身對於 form 有幾個好用的函式庫,這次要用有 FormGroup, FormBuilder,以及內建驗證器 Validators

login.component.ts 分別 import 上述的函式庫,

import { FormGroup, FormBuilder, Validators } from "@angular/forms";

建構式公開使用 FormBuilder 函式

constructor(
public formBuilder: FormBuilder
){}

給 email 跟 password 預設值

email = true;
password = true;

使用表單內容

  get f() {
    return this.form.controls;
  }

使用驗證器

因一開始就讓網頁執行驗證器,所以放在 ngOnInit 裡面。

  • this 已經包裝成外面這個方法,也就是 ngOnInit 本身。
  • ngOnInit 裡面的 form 的值是 formBuilder 裡面的 group 屬性,裡面要驗證的內容。
  • 以 email 為例,使用驗證器可以看到是一個陣列型態,第一個位置是一個空值,後面是一個陣列,驗證器 Validators 後面放上要驗證的方法。
    • required 為必填欄位,沒填寫則會跳錯誤訊息。
    • email 為內建的信箱驗證方法。
    • minLength 是最小長度,如果要限定字元數量,就可以放在小括弧內,像這邊練習是最少 6 字元,最大值則是 maxLength。
  ngOnInit(): void {
     // 表單驗證
    this.form = this.formBuilder.group({
         email: ['', [Validators.required,Validators.email]],
      password: ['', [Validators.required, Validators.minLength(6)]],
    });
  }

這樣就完成一個響應式的表單驗證。

Demo https://stackblitz.com/edit/angular-ivy-uas199?file=src/app/app.component.html

參考資料

Angular 10 - Reactive Forms Validation Example

若觀念有錯誤,還請前輩多多指教。


上一篇
Angular - 從零開始 - Day23 - 表單驗證:Template Driven Form
下一篇
Angular - 從零開始 - Day25 - 旅程告一段落,再見不再見
系列文
Angular - 從零開始25
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言