Angular使用總結 --- 以密碼確認為例實現模版驅動表單的自定義校驗


  上一篇 總結了模版驅動表單的基本用法,示例中的校驗使用的是原生HTML5的校驗方式,本文補上自定義校驗的部分。

  HTML5原生的表單校驗屬性(必填,長度限制,取值間隔,正則表達式等等)可以滿足普通的校驗需求,但是有些場景必須用到自定義校驗,比如注冊時的密碼確認,有比對關系的時間/數值選擇, 需要到請求到服務端取值驗證等等···這里以密碼確認為例進行說明。

指令開發

  表單的驗證狀態是通過 formContro l的 errors 屬性反饋出來的,所以基本的思路肯定就是需要添加校驗規則,然后將驗證結果添加到formControl實例的errors屬性中。那么問題來了,模版驅動表單的控制都是在HTML模版中完成的,無法直接接觸到 formControl實例。這個時候就需要使用指令了,將檢驗規則進行包裝。Angular提供了 驗證器供應商 NG_VALIDATORS ,用於處理表單自定義校驗。先創建指令。

import { Directive} from '@angular/core';
import { NG_VALIDATORS, Validator, AbstractControl} from '@angular/forms';

@Directive({
  selector: '[appConfirmpsw]',
 providers: [{ provide : NG_VALIDATORS, useExisting : ConfirmpswDirective, multi: true }]
})
export class ConfirmpswDirective implements Validator {

  constructor() {

   }
  validate(control: AbstractControl): {[key: string]: any} {
     //檢驗規則
  }
}

  1、為指令指定供應商  NG_VALIDATORS , 和別名類 ConfirmpswDirective , 及 multi 為true(可以用同一個token,注冊不同的 provide)。因為是在 NG_VALIDATORS 提供商中注冊的指令,所以才能被Angular的驗證流程識別,需要注意的是要用useExisting來注冊,這樣就不會創建一個新的實例。

  2、用 Validator接口來約束 自定義的指令,這是Angular提供的驗證器的類 。有validate屬性,會傳入表單的formControl,返回 ValidationErrors 對象。

 

  現在指令結構完成,開始進行校驗部分。首先需要傳入已輸入的密碼,所以增加@input,再指定校驗規則,判斷綁定表單的值和傳入的已輸入值是否相同

@Input('appConfirmpsw') confirmpsw: string;

  為了避免使用指令時,還需要額外傳入confirmpsw屬性 ( <input type="password" appConfirmpsw  [confirmpsw]="'xxx'" >),所以我們將 指令名稱appConfirmpsw作為confirmpsw的別名,這樣傳值會比較方便,簡化為  <input type="password" [appConfirmpsw] = "'xxx'">。

  這里專門寫一個檢驗函數,用來比對值和返回結果。記得在指令的validate中調用一下

export function comfirmPswValidator(_confirmpsw: string): ValidatorFn { //傳入已輸入的密碼值 , 返回一個ValidatorFn
  return (control: AbstractControl): {[key: string]: any} => {  //傳入綁定表單的formControl
    if ( !control.value ) { //如果綁定未輸入值,則返回 required錯誤
      return { 'required' : true };
    }
  //如果兩次輸入的值不相同,則返回confirmpsw的錯誤
return control.value !== _confirmpsw ? {'confirmpsw' : {value: true}} : null; }; }

  完整指令如下:

import { Directive, Input } from '@angular/core';
import { NG_VALIDATORS, Validator, AbstractControl, ValidatorFn} from '@angular/forms';

@Directive({
  selector: '[appConfirmpsw]',
  providers: [{
    provide : NG_VALIDATORS,
    useExisting : ConfirmpswDirective,
    multi: true
  }]
})
export class ConfirmpswDirective implements Validator {

  @Input('appConfirmpsw') confirmpsw: string;
  constructor() {

   }
  validate(control: AbstractControl): {[key: string]: any} {
    console.log(this.confirmpsw);
    return this.confirmpsw ? comfirmPswValidator(this.confirmpsw)(control) : null;
  }
}

export function comfirmPswValidator(_confirmpsw: string): ValidatorFn {
  return (control: AbstractControl): {[key: string]: any} => {
    if ( !control.value ) {
      return { 'required' : true };
    }
    return control.value !== _confirmpsw ? {'confirmpsw' : {value: true}} : null;
  };
}

 使用

  測試一下指令的效果吧

    <div class="input-group">
      <label class="group-label" for="psw-new">&emsp;新密碼 :</label>
      <input class="group-input" [(ngModel)]="inputpsw.new" #new="ngModel" type="password" name="psw" id="psw-new" required>
    </div>
    <div class="input-group input-error" *ngIf="new.touched&&new.invalid">
      <div class="group-error-content" *ngIf="new.errors?.required">確認密碼為必填項!</div>
    </div>
    <div class="input-group">
      <label class="group-label" for="psw-confirm">確認密碼 :</label>
      <input class="group-input" [(ngModel)]="inputpsw.confirm" #confirm="ngModel" type="password" name="confirm" id="psw-confirm" [appConfirmpsw] = "new.value"  required>
    </div>
    <div class="input-group input-error" *ngIf="confirm.touched&&confirm.invalid">
      <div class="group-error-content" *ngIf="confirm.errors?.required">新密碼為必填項!</div>
      <div class="group-error-content" *ngIf="confirm.errors?.confirmpsw">密碼輸入不一致!</div>
    </div>

  傳入new表單的值,並通過errors.confirmpsw屬性來控制提示語反饋。密碼輸入不一致,可以正確的校驗到

  

  確認密碼為空時的提示也正確

  

  以上完成了一個自定義驗證器。有不妥當的地方,望大神指正。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM