zoukankan      html  css  js  c++  java
  • 模板驱动表单中的自定义表单验证

    import { Directive, Input, OnChanges, SimpleChanges } from '@angular/core';
    import { AbstractControl, NG_VALIDATORS, Validator, ValidatorFn, Validators } from '@angular/forms';
    
    /** A hero's name can't match the given regular expression */
    export function forbiddenNameValidator(nameRe: RegExp): ValidatorFn {
      return (control: AbstractControl): {[key: string]: any} | null => {
        const forbidden = nameRe.test(control.value);
        return forbidden ? {'forbiddenName': {value: control.value}} : null;
      };
    }
    
    @Directive({
      selector: '[appForbiddenName]',
      providers: [{provide: NG_VALIDATORS, useExisting: ForbiddenValidatorDirective, multi: true}]
    })
    export class ForbiddenValidatorDirective implements Validator {
      @Input('appForbiddenName') forbiddenName: string;
    
      validate(control: AbstractControl): {[key: string]: any} | null {
        return this.forbiddenName ? forbiddenNameValidator(new RegExp(this.forbiddenName, 'i'))(control)
                                  : null; }
    }

     app.module.ts 引入 自定义指令 

    表单中使用验证指令和验证错误时的提示

  • 相关阅读:
    c++ 的几种强制转换的讨论
    观察者模式
    epoll实现linux进程通信
    vim 实现 go to definition的功能
    svn 的使用
    makefile文件的技术
    [转]epoll技术
    [转]poll技术
    Linux重定向的理解
    避免僵死进程的方法
  • 原文地址:https://www.cnblogs.com/isylar/p/13177305.html
Copyright © 2011-2022 走看看