码迷,mamicode.com
首页 > 其他好文 > 详细

[Angular2 Form] Angular 2 Template Driven Form Custom Validator

时间:2016-10-28 20:19:52      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:war   tutorial   ring   sys   this   ref   rate   provider   can   

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>

 

[Angular2 Form] Angular 2 Template Driven Form Custom Validator

标签:war   tutorial   ring   sys   this   ref   rate   provider   can   

原文地址:http://www.cnblogs.com/Answer1215/p/6008975.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!