やること
- Angular Materialをつかって入力値のValidationチェックを行う
- チェック内容は複数あるものとし、エラーが複数ある場合は、エラーのうちの一つに対応するメッセージを表示する
- チェックは
Validators
に含まれているものに加え、独自のチェックを追加する
環境
- node:14.11.0
- Angular:10.1.1
ソース
やっていることは以下
- エラーメッセージ付きの入力エリアを用意
- 各Validationチェックの結果をDIVエリアに表示
- 入力エリアの変更時にコンソールログにエラーオブジェクトの内容を表示
テンプレート作成
ng g component custom-check-input
Component
Html
Validatorsの持つチェックメソッドがキャメルケース(camel case:ex. minL
ength)なのに対し、FormControl.hasError
でアクセスするオブジェクトのプロパティ名はローワーケース(lower case:ex. minl
ength)であることに注意。
<div style="margin: 10px">
<mat-form-field style="width:200px">
<mat-label>Custom Check</mat-label>
<input matInput [formControl]="formControl" placeholder="Ex. 0123456789" (change)="logError()">
<mat-error *ngIf="hasError()">
<ng-container [ngSwitch]="errorName()">
<ng-container *ngSwitchCase="'required'">{{name}} is required</ng-container>
<ng-container *ngSwitchCase="'minlength'">{{name}} must be at least {{minlength}} characters long</ng-container>
<ng-container *ngSwitchCase="'maxlength'">{{name}} can be max {{maxlength}} characters long</ng-container>
<ng-container *ngSwitchCase="'pattern'">Please match the requested format {{pattern}}</ng-container>
<ng-container *ngSwitchCase="'reserved'">{{formControl.value}} is reserved</ng-container>
</ng-container >
</mat-error>
</mat-form-field>
<div>required : {{formControl.hasError('required')}}</div>
<div>minlength: {{formControl.hasError('minlength')}}</div>
<div>maxlength: {{formControl.hasError('maxlength')}}</div>
<div>pattern : {{formControl.hasError('pattern')}}</div>
<div>reserved : {{formControl.hasError('reserved')}}</div>
</div>
Typescript
import { Component, OnInit } from '@angular/core';
import { FormControl, Validators } from '@angular/forms';
import { CustomValidators } from './custom-varidators';
@Component({
selector: 'app-custom-check-input',
templateUrl: './custom-check-input.component.html',
styleUrls: ['./custom-check-input.component.css']
})
export class CustomCheckInputComponent implements OnInit {
name:string = "field"
minlength:number = 10
maxlength:number = 10
pattern:string = "[0-9]+"
formControl = new FormControl('', [
Validators.required,
Validators.minLength(this.minlength),
Validators.maxLength(this.maxlength),
Validators.pattern(this.pattern),
CustomValidators.reserved
])
constructor() { }
ngOnInit(): void {
}
errorName(): string {
if (this.formControl.errors) {
return Object.keys(this.formControl.errors)[0]
} else {
return ""
}
}
hasError(): boolean {
if (this.formControl.errors) {
return Object.keys(this.formControl.errors).length > 0
} else {
return false
}
}
logError(): void {
if (this.formControl.errors) {
console.table(this.formControl.errors)
}
}
}
Custom Check Class
入力した値が0123456789
と一致していたらエラーになる。
import { AbstractControl, ValidationErrors } from '@angular/forms';
export class CustomValidators {
static reserved(control: AbstractControl) : ValidationErrors | null {
if(control.value as string == "0123456789"){
return {reserved: true}
}
return null;
}
}
結果
参考
Validationチェックの公式サンプル

Angular Material
UI component infrastructure and Material Design components for Angular web applications.
Validatorsの持つチェック関数
Angular
Custom Validatorsの追加方法
How to Create Custom Validators in Angular 9/8?
how to create custom form validator in angular 9/8, angular 9/8 custom validator example, custom validation in angular 9/8 reactive form, angular 9/8 custom val...