使用Angular自定义字段校验指令
栏目: JavaScript · 发布时间: 6年前
内容简介:Angular中,提供的表单验证不能用于所有应用场景,就需要创建自定义验证器,比如对IP、MAC的合法性校验这里是根据
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 选择器添加到输入框上就可以激活这个验证器。
在模板中使用
<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官网表单验证自定义验证器部分。
以上所述就是小编给大家介绍的《使用Angular自定义字段校验指令》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:- vue实战 - 车牌号校验和银行校验
- 更加灵活的参数校验,Spring-boot自定义参数校验注解
- 一坨一坨的 if/else 参数校验,终于被 Spring Boot 参数校验组件整干净了
- SpringMVC——数据校验
- gin请求数据校验
- Dojo 表单校验
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Iterative Methods for Sparse Linear Systems, Second Edition
Yousef Saad / Society for Industrial and Applied Mathematics / 2003-04-30 / USD 102.00
Tremendous progress has been made in the scientific and engineering disciplines regarding the use of iterative methods for linear systems. The size and complexity of linear and nonlinear systems arisi......一起来看看 《Iterative Methods for Sparse Linear Systems, Second Edition》 这本书的介绍吧!