[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>

 

posted @   Zhentiw  阅读(259)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2015-10-28 [Angular 2] Using Pipes to Filter Data
2015-10-28 [Angular 2] Controlling how Styles are Shared with View Encapsulation
2015-10-28 [Angular 2] ng-class and Encapsulated Component Styles
2013-10-28 Dynamic Programming for TSP
点击右上角即可分享
微信分享提示