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