Angular4(2+)でカスタムValidationを作る
Angular4(2+)で独自のValidationを作ってフォームに適用したい時のやり方を調べましたので、備忘録として残しておきます。
1. Validationディレクティブを作成する。
まず、ディレクティブとして、カスタムValidationを実装したクラスを作ります。 以下は単純な例で、フォームへの入力値が「abc」だったらNG、それ以外はOKとしてます。
import { Directive } from '@angular/core'; import { AbstractControl, FormControl, ValidationErrors } from '@angular/forms'; @Directive({ selector: '[validateCustom][ngModel],[validatorCustom][formControl]' }) export class CustomValidator { check(control: AbstractControl): ValidationErrors|null { return control.value === 'abc' ? {‘custom': true} : null; } }
入力をNGとしたい時に「{‘項目名’: true}」をreturnします。
参考:angular.coreのソース
https://github.com/angular/angular/blob/71f5b73296708014b740fb5dd0145c0599de7a19/packages/forms/src/validators.ts
2. 作ったカスタムValidationを使う。
使いたいコンポーネントの中で以下のように書くことで使用できます。
import ‘CustomValidator’ from ‘../directives/custom-validator'; : onNgInit() { const cv = new CustomValidator(); this.control = new FormControl('', cv.check); }