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

[Angular2 Form] Model Driven Form Custom Validator

时间:2016-10-28 20:30:22      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:using   orm   span   ted   class   exp   type   ...   require   

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>

 

[Angular2 Form] Model Driven Form Custom Validator

标签:using   orm   span   ted   class   exp   type   ...   require   

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

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