[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>
原文地址:https://www.cnblogs.com/Answer1215/p/6008907.html