首页 > 代码库 > [Angular2 Form] Angular 2 Template Driven Form Custom Validator
[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>
[Angular2 Form] Angular 2 Template Driven Form Custom Validator
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。