Angular實現(xiàn)模版驅(qū)動表單的自定義校驗功能(密碼確認為例)
HTML5原生的表單校驗屬性(必填,長度限制,取值間隔,正則表達式等等)可以滿足普通的校驗需求,但是有些場景必須用到自定義校驗,比如注冊時的密碼確認,有比對關(guān)系的時間/數(shù)值選擇, 需要到請求到服務(wù)端取值驗證等等···這里以密碼確認為例進行說明。
指令開發(fā)
表單的驗證狀態(tài)是通過 formContro l的 errors 屬性反饋出來的,所以基本的思路肯定就是需要添加校驗規(guī)則,然后將驗證結(jié)果添加到formControl實例的errors屬性中。那么問題來了,模版驅(qū)動表單的控制都是在HTML模版中完成的,無法直接接觸到 formControl實例。這個時候就需要使用指令了,將檢驗規(guī)則進行包裝。Angular提供了 驗證器供應(yīng)商 NG_VALIDATORS ,用于處理表單自定義校驗。先創(chuàng)建指令。
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} {
//檢驗規(guī)則
}
}
1、為指令指定供應(yīng)商 NG_VALIDATORS , 和別名類 ConfirmpswDirective , 及 multi 為true(可以用同一個token,注冊不同的 provide)。因為是在 NG_VALIDATORS 提供商中注冊的指令,所以才能被Angular的驗證流程識別,需要注意的是要用useExisting來注冊,這樣就不會創(chuàng)建一個新的實例。
2、用 Validator接口來約束 自定義的指令,這是Angular提供的驗證器的類 。有validate屬性,會傳入表單的formControl,返回 ValidationErrors 對象。
現(xiàn)在指令結(jié)構(gòu)完成,開始進行校驗部分。首先需要傳入已輸入的密碼,所以增加@input,再指定校驗規(guī)則,判斷綁定表單的值和傳入的已輸入值是否相同
@Input('appConfirmpsw') confirmpsw: string;
為了避免使用指令時,還需要額外傳入confirmpsw屬性 ( <input type="password" appConfirmpsw [confirmpsw]="'xxx'" >),所以我們將 指令名稱appConfirmpsw作為confirmpsw的別名,這樣傳值會比較方便,簡化為 <input type="password" [appConfirmpsw] = "'xxx'">。
這里專門寫一個檢驗函數(shù),用來比對值和返回結(jié)果。記得在指令的validate中調(diào)用一下
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"> 新密碼 :</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屬性來控制提示語反饋。密碼輸入不一致,可以正確的校驗到

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

總結(jié)
以上所述是小編給大家介紹的Angular實現(xiàn)模版驅(qū)動表單的自定義校驗功能(密碼確認為例),希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
詳解Angular CLI + Electron 開發(fā)環(huán)境搭建
本篇文章主要介紹了Angular CLI + Electron 開發(fā)環(huán)境搭建,具有一定的參考價值,有興趣的可以了解一下2017-07-07
Angular通過?HTTP?Interceptor?實現(xiàn)?HTTP?請求超時監(jiān)控的例子
這篇文章主要介紹了Angular?如何通過?HTTP?Interceptor?實現(xiàn)?HTTP?請求的超時監(jiān)控,本文通過例子給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-06-06
詳解使用angular-cli發(fā)布i18n多國語言Angular應(yīng)用
這篇文章主要介紹了詳解使用angular-cli發(fā)布i18n多國語言Angular應(yīng)用,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-05-05
angularJS 發(fā)起$http.post和$http.get請求的實現(xiàn)方法
本篇文章主要介紹了angularJS 發(fā)起$http.post和$http.get請求的實現(xiàn)方法,分別介紹了$http.post和$http.get請求的方法,有興趣的可以了解一下2017-05-05

