Angular中,提供的表單驗證不能用于所有應用場景,就需要創建自定義驗證器,比如對IP、MAC的合法性校驗
這里是根據官網實例自定義MAC地址的正則校驗,環境為Angular: 7.2.0 , NG-ZORRO:v7.0.0-rc3
添加指令
/shared/validator.directive.ts
注冊到 NG_VALIDATORS 提供商中
providers: [ {provide: NG_VALIDATORS, useExisting: ValidatorDirective, multi: true} ]
Angular 在驗證流程中的識別出指令的作用,是因為指令把自己注冊到了 NG_VALIDATORS 提供商中,該提供商擁有一組可擴展的驗證器。
實現 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 選擇器添加到輸入框上就可以激活這個驗證器。
在模板中使用
首先在模板所在的module中引入該指令
import {ValidatorDirective} from "../../shared/validator.directive";@NgModule({ imports: [ SharedModule ], declarations: [ ValidatorDirective ], providers: [ AuthGuard ],})
在html中使用
<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,如下:
<nz-form-explain *ngIf="validateForm.get('mac').dirty && validateForm.get('mac').errors&&validateForm.get('mac').touched"> 請輸入正確的Mac地址! </nz-form-explain>
到此,自定義字段驗證指令就完成了,更多請查看Angular官網表單驗證自定義驗證器部分。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答