Angular5+ 自定義表單驗證器

来源:https://www.cnblogs.com/jehorn/archive/2018/09/21/9687501.html
-Advertisement-
Play Games

Angular自定義表單驗證器 - 怎樣實現“再次輸入密碼”的驗證(兩個controller值相等)(equalTo) ...


Angular5+ 自定義表單驗證器

Custom Validators

標簽(空格分隔): Angular


首先闡述一下遇到的問題:

  • 怎樣實現“再次輸入密碼”的驗證(兩個controller值相等)(equalTo)
  • 怎樣反向監聽(先輸入“再次輸入密碼”,後輸入設置密碼)

解決思路:

  • 第一個問題,可以通過[AbstractControl].root.get([targetName])來取得指定的controller,然後比較他們的值。
  • 第二個,可以通過[target].setErrors([errors])來實現。
  1. 這是一個我的自定義表單驗證:
import {AbstractControl, FormGroup, ValidatorFn} from '@angular/forms';
import {G} from '../services/data-store.service';

export class MyValidators {
  private static isEmptyInputValue(value) {
    // we don't check for string here so it also works with arrays
    return value == null || value.length === 0;
  }
  private static isEmptyObject(obj) {
    if (typeof obj === 'object' && typeof obj.length !== 'number') {
      return Object.keys(obj).length === 0;
    }
    return null;
  }

  /**
   * 等於指定controller的值
   * @param targetName 目標的formControlName
   * @returns {(ctrl: FormControl) => {equalTo: {valid: boolean}}}
   */
  static equalTo(targetName: string): ValidatorFn {
    return (control: AbstractControl): {[key: string]: any} | null => {
      const target = control.root.get(targetName);
      if (target === null) {
        return null;
      }
      if (this.isEmptyInputValue(control.value)) {
        return null;
      }
      return target.value === control.value ? null : {'equalto': { valid: false }};
    };
  }

  /**
   * 反向輸入監聽指定controller是否與當前值相等
   * @param targetName
   */
  static equalFor(targetName: string): ValidatorFn {
    return (control: AbstractControl): {[key: string]: any} | null => {
      const target = control.root.get(targetName);
      if (target === null) {
        return null;
      }
      if (this.isEmptyInputValue(control.value)) {
        return null;
      }
      if (target.value === control.value) {
        const errors = target.errors;
        delete errors['equalto'];

        if (this.isEmptyObject(errors)) {
          target.setErrors(null);
        } else {
          target.setErrors(errors);
        }
        return null;
      }
      target.setErrors({ 'equalto': { valid: false } });
    };
  }

  ...
}

(註:)其中G.REGEX等的是全局變數。

  1. 然後FormBuilder來實現:
import { Component, OnInit } from '@angular/core';
import {EventsService} from '../../../services/events.service';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {G} from '../../../services/data-store.service';
import {fade} from '../../../animations/fade.animation';
import {MyValidators} from '../../../directives/my-validators.directive';

@Component({
  selector: 'app-sign-up',
  templateUrl: './sign-up.component.html',
  styleUrls: ['./sign-up.component.scss'],
  animations: [fade]
})
export class SignUpComponent implements OnInit {
  signForm: FormGroup; // 表單組FormGroup
  submitting: boolean; // 是否可以提交
  validations = G.VALIDATIONS;

  constructor(private eventsService: EventsService, private formBuilder: FormBuilder) {
    this.submitting = false;

    // 
    this.init();
  }

  ngOnInit() {
    // 設置父組件標題
    this.eventsService.publish('setSign', { title: '註冊', subTitle: { name: '立即登錄', uri: '/account/sign-in' } });
  }

  // 立即註冊
  onSubmit() {
    console.log(this.signForm.getRawValue());
  }

  // 表單初始化
  private init() {
    this.signForm = this.formBuilder.group({
      username: ['', Validators.compose([Validators.required, Validators.maxLength(this.validations.USR_MAX)])],
      password: ['', Validators.compose([
        Validators.required,
        Validators.minLength(this.validations.PASS_MIN),
        Validators.maxLength(this.validations.PASS_MAX),
        MyValidators.equalFor('passwordConfirm')
      ])],
      passwordConfirm: ['', Validators.compose([
        Validators.required,
        Validators.minLength(this.validations.PASS_MIN),
        Validators.maxLength(this.validations.PASS_MAX),
        MyValidators.equalTo('password')
      ])]
    });
  }
}

(註:)其中fade動畫效果。

  1. 然後在html模板中,顯示表單驗證提示信息:
<form [formGroup]="signForm" (ngSubmit)="onSubmit()" class="sign-form" @fade>

  <!-- 賬號 -->
  <div class="input-group username">
    <span class="addon prev"><i class="civ civ-i-usr"></i></span>
    <input type="text"
      name="username"
      class="form-control form-control-left default"
      placeholder="請輸入賬號"
      formControlName="username"
      autocomplete="off">
    <ul class="errors" *ngIf="signForm.get('username').invalid && (signForm.get('username').dirty || signForm.get('username').touched)">
      <li *ngIf="signForm.get('username').hasError('required')" class="error">
        請輸入您的賬號!
      </li>
      <li *ngIf="signForm.get('username').hasError('maxlength')" class="error">
        賬號不超過{{ validations.USR_MAX }}位!
      </li>
    </ul>
  </div> <!-- /.賬號 -->
  
  <!-- 密碼 -->
  <div class="input-group password">
    <span class="addon prev"><i class="civ civ-i-lock"></i></span>
    <input type="password"
      name="password"
      class="form-control form-control-left default"
      placeholder="請輸入密碼"
      formControlName="password">
    <ul class="errors" *ngIf="signForm.get('password').invalid && (signForm.get('password').dirty || signForm.get('password').touched)">
      <li *ngIf="signForm.get('password').hasError('required')" class="error">
        請輸入您的密碼!
      </li>
      <li *ngIf="signForm.get('password').hasError('minlength')" class="error">
        請輸入至少{{ validations.PASS_MIN }}位數的密碼!
      </li>
      <li *ngIf="signForm.get('password').hasError('maxlength')" class="error">
        密碼不超過{{ validations.PASS_MAX }}位!
      </li>
    </ul>
  </div> <!-- /.密碼 -->
  
  <!-- 重覆密碼 -->
  <div class="input-group password-confirm">
    <span class="addon prev"><i class="civ civ-i-lock"></i></span>
    <input type="password"
           name="passwordConfirm"
           class="form-control form-control-left default"
           placeholder="請再次輸入密碼"
           formControlName="passwordConfirm">
    <ul class="errors" *ngIf="signForm.get('passwordConfirm').invalid && (signForm.get('passwordConfirm').dirty || signForm.get('passwordConfirm').touched)">
      <li *ngIf="signForm.get('passwordConfirm').hasError('required')" class="error">
        請再次輸入密碼!
      </li>
      <li *ngIf="signForm.get('passwordConfirm').hasError('minlength')" class="error">
        請輸入至少{{ validations.PASS_MIN }}位數的密碼!
      </li>
      <li *ngIf="signForm.get('passwordConfirm').hasError('maxlength')" class="error">
        密碼不超過{{ validations.PASS_MAX }}位!
      </li>
      <li *ngIf="!signForm.get('passwordConfirm').hasError('maxlength') && !signForm.get('passwordConfirm').hasError('minlength') && signForm.get('passwordConfirm').hasError('equalto')" class="error">
        兩次密碼輸入不一致!
      </li>
    </ul>
  </div> <!-- /.重覆密碼 -->
  
  <!-- 提交按鈕 -->
  <button type="submit"
          class="btn btn-primary btn-block submit"
          [disabled]="submitting || signForm.invalid">立即註冊</button>
  <!-- /.提交按鈕 -->
  
</form>

最後,我們可以看到,實現了想要的效果:

效果圖







(附:)完整的自定義表單驗證器:

import {AbstractControl, FormGroup, ValidatorFn} from '@angular/forms';
import {G} from '../services/data-store.service';

export class MyValidators {
  private static isEmptyInputValue(value) {
    // we don't check for string here so it also works with arrays
    return value == null || value.length === 0;
  }
  private static isEmptyObject(obj) {
    if (typeof obj === 'object' && typeof obj.length !== 'number') {
      return Object.keys(obj).length === 0;
    }
    return null;
  }

  /**
   * 等於指定controller的值
   * @param targetName 目標的formControlName
   * @returns {(ctrl: FormControl) => {equalTo: {valid: boolean}}}
   */
  static equalTo(targetName: string): ValidatorFn {
    return (control: AbstractControl): {[key: string]: any} | null => {
      const target = control.root.get(targetName);
      if (target === null) {
        return null;
      }
      if (this.isEmptyInputValue(control.value)) {
        return null;
      }
      return target.value === control.value ? null : {'equalto': { valid: false }};
    };
  }

  /**
   * 反向輸入監聽指定controller是否與當前值相等
   * @param targetName
   */
  static equalFor(targetName: string): ValidatorFn {
    return (control: AbstractControl): {[key: string]: any} | null => {
      const target = control.root.get(targetName);
      if (target === null) {
        return null;
      }
      if (this.isEmptyInputValue(control.value)) {
        return null;
      }
      if (target.value === control.value) {
        const errors = target.errors;
        delete errors['equalto'];

        if (this.isEmptyObject(errors)) {
          target.setErrors(null);
        } else {
          target.setErrors(errors);
        }
        return null;
      }
      target.setErrors({ 'equalto': { valid: false } });
    };
  }

  /**
   * 驗證手機號
   * @returns {(ctrl: FormControl) => {mobile: {valid: boolean}}}
   */
  static get mobile() {
    return (control: AbstractControl) => {
      if (this.isEmptyInputValue(control.value)) {
        return null;
      }

      const valid = G.REGEX.MOBILE.test(control.value);

      return valid ? null : {
        'mobile': {
          valid: false
        }
      };
    };
  }

  /**
   * 驗證身份證
   * @returns {(ctrl: FormControl) => {idCard: {valid: boolean}}}
   */
  static get idCard() {
    return (control: AbstractControl) => {
      if (this.isEmptyInputValue(control.value)) {
        return null;
      }

      const valid = G.REGEX.ID_CARD.test(control.value);

      return valid ? null : {
        'idcard': {
          valid: false
        }
      };
    };
  }

  /**
   * 驗證漢字
   * @returns {(ctrl: FormControl) => {cn: {valid: boolean}}}
   */
  static get cn() {
    return (control: AbstractControl) => {
      if (this.isEmptyInputValue(control.value)) {
        return null;
      }

      const valid = G.REGEX.CN.test(control.value);

      return valid ? null : {
        'cn': {
          valid: false
        }
      };
    };
  }

  /**
   * 指定個數數字
   * @param {number} length
   * @returns {(ctrl: FormControl) => (null | {number: {valid: boolean}})}
   */
  static number(length: number = 6) {
    return (control: AbstractControl) => {
      if (this.isEmptyInputValue(control.value)) {
        return null;
      }

      const valid = new RegExp(`^\\d{${length}}$`).test(control.value);

      return valid ? null : {
        'number': {
          valid: false
        }
      };
    };
  }

  /**
   * 強密碼(必須包含數字字母)
   * @returns {(ctrl: FormControl) => (null | {number: {valid: boolean}})}
   */
  static get strictPass() {
    return (control: AbstractControl) => {
      if (this.isEmptyInputValue(control.value)) {
        return null;
      }

      const valid = G.REGEX.STRICT_PASS.test(control.value);

      return valid ? null : {
        'strictpass': {
          valid: false
        }
      };
    };
  }
}

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • OTA 軟體包工具 本文地址 "http://wossoneri.github.io/2018/09/21/%5BAndroid%5D%5BFramework%5Dcreate ota update zip/" 中提供的 ota_from_target_files 工具可以構建兩種類型的軟體包:完整 ...
  • 相似點 1.函數指針和Block都可以實現回調的操作,聲明上也很相似,實現上都可以看成是一個代碼片段。 2.函數指針類型和Block類型都可以作為變數和函數參數的類型。(typedef定義別名之後,這個別名就是一個類型) 不同點 1.函數指針只能指向預先定義好的函數代碼塊(可以是其他文件裡面定義,通 ...
  • 前言 這裡主要介紹一下Xcode10 版本主要更新的內容。 隨著iOS12的發佈,Xcode10已經可以從Mac App Store下載。 Xcode10包含了iOS12、watchOS 5、macOS10.14以及tvOS 12的SDK。另外,開發者可以從Xcode中看到當前Deployment ...
  • 什麼是小程式·雲開發 小程式·雲開發是微信團隊和騰訊雲團隊共同研發的一套小程式基礎能力,簡言之就是:雲能力將會成為小程式的基礎能力。整套功能是基於騰訊雲全新推出的雲開發(Tencent Cloud Base)所研發出來的一套完備的小程式後臺開發方案。 小程式·雲開發為開發者提供完整的雲端流程,簡化後 ...
  • JavaScript比較和邏輯運算符 JavaScript比較和邏輯運算符 比較和邏輯運算符用於測試true或者false。 比較運算符 比較運算符在邏輯語句中使用,以測定變數或值是否相等 可以在條件語句中使用比較運算符,對值進行比較,然後根據結果採取行動。 例如:if(age > 18) { al ...
  • "阮一峰ES6入門" let 作用域 let命令用來聲明變數,但聲明的變數只在let命令所在的代碼塊內有效。 for迴圈 上圖代碼中i是var聲明的,在全局範圍內部有效,所以全局只有一個變數i。 每一次迴圈,變數i的值都會發生改變,而迴圈內被賦給數組a的函數內部的console.log(i),裡面的 ...
  • applyDefaultStyles: true,//應用預設樣式 scrollToBookmarkOnLoad:false,//頁載入時滾動到標簽 showOverflowOnHover:false,//滑鼠移過顯示被隱藏的,只在禁用滾動條時用。 north__closable:false,//可... ...
  • {{ item.com || "--"}} ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...