[Angular2 Form] Model Driven Form Custom Validator

In this tutorial we are going to learn how simple it is to create custom form field driven validators while using Angular 2 model driven forms. These type of validators are really just plain functions that follow a set of conventions.

We are going to learn how to write a custom form validator and what the validating function needs to return in order to respect the Angular 2 form field validation contract.

 

Define a custom validator:

复制代码
import {FormControl} from "@angular/forms";

export function validateDuration(ctrl:FormControl){
  
  const numValue = parseInt(ctrl.value);
  const valid = numValue < 10;

  return valid ? null : {
    validateDuration: {
      valid: false,
      message: "Duration should less than 10"
    }
  }
}
复制代码

It just a function which return null or object, is it has error, it should return an object. 

 

复制代码
this.reactiveForm = fb.group({
      ...
      duration: [
        0,
        [
          Validators.required,
          //Validators.pattern('[0-9]+'),
          validateDuration
        ]
      ],
      ...
    });
复制代码

We add 'validateDuration' into our validators array.

 

Use it:

  <div class="form-field">
    <label>Duration:</label>
    <input formControlName="duration">
    <div *ngIf="reactiveForm.controls.duration.errors?.validateDuration">
       {{reactiveForm.controls.duration.errors?.validateDuration.message}}
    </div>
  </div>

 

posted @   Zhentiw  阅读(267)  评论(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
点击右上角即可分享
微信分享提示