zoukankan      html  css  js  c++  java
  • [Angular2 Form] Angular 2 Template Driven Form Custom Validator

    In this tutorial we are going to learn how we can also implement custom form field validation in Angular 2 template driven forms, by creating our own custom validation directive. We are going to see how to write such directive and how its a best practive to extract the validation function to a separate function, so that it can also be used for model driven validation.

    We are going to learn how we can configure the template driven custom validator directive into the Angular 2 Forms mechanism, by plugging the directive into the dependency injection system using NG_VALIDATORS and forwardRef.

    import {Validator, NG_VALIDATORS, FormControl} from "@angular/forms";
    import {validateDuration} from "./validateDuration";
    import {Directive, forwardRef} from "@angular/core";
    
    export const MIN_LENGTH_VALIDATOR = {
      provide: NG_VALIDATORS,
      multi: true,
      useExisting: forwardRef(() => DurationValidator)
    };
    
    // target and duration with ngModel
    @Directive({
      selector: '[duration][ngModel]',
      providers: [MIN_LENGTH_VALIDATOR]
    })
    export class DurationValidator implements Validator {
      validate(c: FormControl): {[key: string]:any} {
        return validateDuration(c);
      }
    }

    use:

     Duration: <input type="number" name="duration" [(ngModel)]="duration" duration required>
  • 相关阅读:
    网上购物记录(2011淘宝大甩卖)
    心理学上最诡异的23张图!!
    三字念什么
    哥德尔不完备定理
    又要新的开始了(续)
    第一次接触计算机语言的经历
    哥德尔不完备性定理——从数学危机到哲学危机
    google (精简版)
    贴吧回复
    在轻松的环境中工作
  • 原文地址:https://www.cnblogs.com/Answer1215/p/6008975.html
Copyright © 2011-2022 走看看