• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

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

angularjs 搞代码 4年前 (2021-12-31) 37次浏览 已收录 0个评论

这篇文章主要介绍了使用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['v<b style="color:transparent">来源gao@dai!ma.com搞$代^码网</b>alue']) ? null : {validate: true}; break; } } } 

ValidatorDirective写好后,只要把 appValidator 选择器添加到输入框上就可以激活这个验证器。

在模板中使用

首先在模板所在的module中引入该指令

 import {ValidatorDirective} from "../../shared/validator.directive"; @NgModule({ imports: [ SharedModule ], declarations: [ ValidatorDirective ], providers: [ AuthGuard ], }) 

在html中使用

     请输入正确的Mac地址! 

在mac地址校验不通过时,错误信息便会显示。如果想在失去焦点时显示错误信息可以使用validateForm.get(‘mac’).touched,如下:

  请输入正确的Mac地址! 

到此,自定义字段验证指令就完成了,更多请查看Angular官网表单验证自定义验证器部分。

以上就是使用Angular自定义字段校验指令的方法示例的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:使用Angular自定义字段校验指令的方法示例

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址