zoukankan      html  css  js  c++  java
  • [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>
  • 相关阅读:
    阅读《构建之法(第三版)》提出的问题
    职位部门管理系统
    JSON
    hashcode()和equals()方法
    JSF和Facelets的生命周期
    认识applet
    认识ajax
    hello1.java分析
    vue中的防抖和节流
    vue项目搭建
  • 原文地址:https://www.cnblogs.com/Answer1215/p/6008907.html
Copyright © 2011-2022 走看看