• 技术文章 >web前端 >js教程

    如何操作Angular实现模版驱动表单的自定义校验功能

    php中世界最好的语言php中世界最好的语言2018-05-29 10:36:31原创585
    这次给大家带来如何操作Angular实现模版驱动表单的自定义校验功能,操作Angular实现模版驱动表单的自定义校验功能的注意事项有哪些,下面就是实战案例,一起来看一下。

    HTML5原生的表单校验属性(必填,长度限制,取值间隔,正则表达式等等)可以满足普通的校验需求,但是有些场景必须用到自定义校验,比如注册时的密码确认,有比对关系的时间/数值选择, 需要到请求到服务端取值验证等等···这里以密码确认为例进行说明。

    指令开发

      表单的验证状态是通过 formContro l的 errors 属性反馈出来的,所以基本的思路肯定就是需要添加校验规则,然后将验证结果添加到formControl实例的errors属性中。那么问题来了,模版驱动表单的控制都是在HTML模版中完成的,无法直接接触到 formControl实例。这个时候就需要使用指令了,将检验规则进行包装。Angular提供了 验证器供应商 NG_VALIDATORS ,用于处理表单自定义校验。先创建指令。

    import { Directive} from '@angular/core';
    import { NG_VALIDATORS, Validator, AbstractControl} from '@angular/forms';
    @Directive({
     selector: '[appConfirmpsw]',
     providers: [{
      provide : NG_VALIDATORS,
      useExisting : ConfirmpswDirective,
      multi: true
     }]
    })
    export class ConfirmpswDirective implements Validator {
     constructor() {
      }
     validate(control: AbstractControl): {[key: string]: any} {
       //检验规则
     }
    }

      1、为指令指定供应商 NG_VALIDATORS , 和别名类 ConfirmpswDirective , 及 multi 为true(可以用同一个token,注册不同的 provide)。因为是在 NG_VALIDATORS 提供商中注册的指令,所以才能被Angular的验证流程识别,需要注意的是要用useExisting来注册,这样就不会创建一个新的实例。

      2、用 Validator接口来约束 自定义的指令,这是Angular提供的验证器的类 。有validate属性,会传入表单的formControl,返回 ValidationErrors 对象。

      现在指令结构完成,开始进行校验部分。首先需要传入已输入的密码,所以增加@input,再指定校验规则,判断绑定表单的值和传入的已输入值是否相同

    @Input('appConfirmpsw') confirmpsw: string;

      为了避免使用指令时,还需要额外传入confirmpsw属性 ( <input type="password" appConfirmpsw [confirmpsw]="'xxx'" >),所以我们将 指令名称appConfirmpsw作为confirmpsw的别名,这样传值会比较方便,简化为 <input type="password" [appConfirmpsw] = "'xxx'">

      这里专门写一个检验函数,用来比对值和返回结果。记得在指令的validate中调用一下

    export function comfirmPswValidator(_confirmpsw: string): ValidatorFn { //传入已输入的密码值 , 返回一个ValidatorFn
     return (control: AbstractControl): {[key: string]: any} => { //传入绑定表单的formControl
      if ( !control.value ) { //如果绑定未输入值,则返回 required错误
       return { 'required' : true };
      }
      //如果两次输入的值不相同,则返回confirmpsw的错误
      return control.value !== _confirmpsw ? {'confirmpsw' : {value: true}} : null;
     };
    }

      完整指令如下:

    import { Directive, Input } from '@angular/core';
    import { NG_VALIDATORS, Validator, AbstractControl, ValidatorFn} from '@angular/forms';
    @Directive({
     selector: '[appConfirmpsw]',
     providers: [{
      provide : NG_VALIDATORS,
      useExisting : ConfirmpswDirective,
      multi: true
     }]
    })
    export class ConfirmpswDirective implements Validator {
     @Input('appConfirmpsw') confirmpsw: string;
     constructor() {
      }
     validate(control: AbstractControl): {[key: string]: any} {
      console.log(this.confirmpsw);
      return this.confirmpsw ? comfirmPswValidator(this.confirmpsw)(control) : null;
     }
    }
    export function comfirmPswValidator(_confirmpsw: string): ValidatorFn {
     return (control: AbstractControl): {[key: string]: any} => {
      if ( !control.value ) {
       return { 'required' : true };
      }
      return control.value !== _confirmpsw ? {'confirmpsw' : {value: true}} : null;
     };
    }

     使用

      测试一下指令的效果吧

     <p class="input-group">
       <label class="group-label" for="psw-new"> 新密码 :</label>
       <input class="group-input" [(ngModel)]="inputpsw.new" #new="ngModel" type="password" name="psw" id="psw-new" required>
      </p>
      <p class="input-group input-error" *ngIf="new.touched&&new.invalid">
       <p class="group-error-content" *ngIf="new.errors?.required">确认密码为必填项!</p>
      </p>
      <p class="input-group">
       <label class="group-label" for="psw-confirm">确认密码 :</label>
       <input class="group-input" [(ngModel)]="inputpsw.confirm" #confirm="ngModel" type="password" name="confirm" id="psw-confirm"
       [appConfirmpsw] = "new.value" required>
      </p>
      <p class="input-group input-error" *ngIf="confirm.touched&&confirm.invalid">
       <p class="group-error-content" *ngIf="confirm.errors?.required">新密码为必填项!</p>
       <p class="group-error-content" *ngIf="confirm.errors?.confirmpsw">密码输入不一致!</p>
      </p>

      传入new表单的值,并通过errors.confirmpsw属性来控制提示语反馈。密码输入不一致,可以正确的校验到

      确认密码为空时的提示也正确

    相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

    推荐阅读:

    如何处理Mac安装thrift因bison报错

    如何使用淘宝镜像cnpm安装Vue.js

    以上就是如何操作Angular实现模版驱动表单的自定义校验功能的详细内容,更多请关注php中文网其它相关文章!

    声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。
    专题推荐:Angular 模版 实现
    上一篇:javaScript实现鼠标在文字上悬浮时弹出悬浮层效果 下一篇:怎样使用AngularJS自定义过滤器用法
    Web大前端开发直播班

    相关文章推荐

    • 一起来分析JavaScript中的弱引用和强引用• 浅析Angular中怎么用 Api 代理• 带你了解JavaScript中的键盘、鼠标事件• Angular利用service实现自定义服务(notification)• 聊聊怎么利用Angular+Jenkins展示构建版本

    全部评论我要评论

  • 取消发布评论发送
  • 1/1

    PHP中文网