使用Angular自定义字段校验指令的方法示例

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>

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/e79ace4cb7fec7448aa404644c62637f.html