首页 > 其他 > 详细

[Angular2 Form] Model Driven Form Custom Validator

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

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!