Angular中,提供的表單驗證不能用於全部應用場景,就須要建立自定義驗證器,好比對IP、MAC的合法性校驗
這裏是根據官網實例自定義MAC地址的正則校驗,環境爲Angular: 7.2.0 , NG-ZORRO:v7.0.0-rc3html
/shared/validator.directive.ts
數組
NG_VALIDATORS
提供商中providers: [ {provide: NG_VALIDATORS, useExisting: ValidatorDirective, multi: true} ]
Angular 在驗證流程中的識別出指令的做用,是由於指令把本身註冊到了 NG_VALIDATORS 提供商中,該提供商擁有一組可擴展的驗證器。app
Validator
接口import {Directive, Input} from '@angular/core'; import {Validator, AbstractControl, NG_VALIDATORS} from '@angular/forms'; @Directive({ selector: '[appValidator]', providers: [ {provide: NG_VALIDATORS, useExisting: ValidatorDirective, multi: true} ] }) export class ValidatorDirective implements Validator { @Input('appValidator') value: string; validate(control: AbstractControl): { [key: string]: any } | null { const validateMac = /^(([A-Fa-f0-9]{2}[:]){5}[A-Fa-f0-9]{2}[,]?)+$/; switch (this.value) { case 'mac': return validateMac.exec(control['value']) ? null : {validate: true}; break; } } }
ValidatorDirective寫好後,只要把 appValidator 選擇器添加到輸入框上就能夠激活這個驗證器。ide
import {ValidatorDirective} from "../../shared/validator.directive"; @NgModule({ imports: [ SharedModule ], declarations: [ ValidatorDirective ], providers: [ AuthGuard ], })
在html中使用ui
<nz-form-item> <nz-form-control> <nz-input-group> <input formControlName="mac" nz-input type="text" placeholder="mac" appValidator="mac"> </nz-input-group> <nz-form-explain *ngIf="validateForm.get('mac').dirty && validateForm.get('mac').errors"> 請輸入正確的Mac地址! </nz-form-explain> </nz-form-control> </nz-form-item>
在mac地址校驗不經過時,錯誤信息便會顯示。若是想在失去焦點時顯示錯誤信息能夠使用validateForm.get('mac').touched
,以下:this
<nz-form-explain *ngIf="validateForm.get('mac').dirty && validateForm.get('mac').errors&&validateForm.get('mac').touched"> 請輸入正確的Mac地址! </nz-form-explain>
<input id="name" name="name" class="form-control" required minlength="4" appValidator="mac" [(ngModel)]="macValue" #name="ngModel" > <div *ngIf="name.errors">請輸入正確的Mac地址!</div>
注: 若是想在多個module使用,須要將該指令添加到module的export數組中,我是在SharedModule中導入的。
到此,自定義字段驗證指令就完成了,更多請查看Angular官網表單驗證自定義驗證器部分。code