首页 > 代码库 > [Angular2 Form] Model Driven Form Custom Validator
[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 =http://www.mamicode.com/ 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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。