ionic で フォームバリデーションを作成する

● フォーム画面 /form/ に フォームバリデーションを作成する

* 1. app/form/form.page.ts へ記述

(モジュールの読み込み)
app/form/form.page.ts

// add
import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';

(エラーメッセージの定義)
app/form/form.page.ts

	validations = {
		'username': [
			{ type: 'required', message: 'お名前は入力必須です' },
		],
		'email': [
			{ type: 'required', message: 'メールアドレスは入力必須です' },
		],
		'content': [
			{ type: 'required', message: 'お問い合わせ内容は入力必須です' },
		],
	};

(バリデーションフォームの定義)
app/form/form.page.ts

	public loginForm: FormGroup;

	constructor(
		public router: Router, 
		public formBuilder: FormBuilder) {

		this.loginForm = new FormGroup({
			username: new FormControl('', Validators.compose([
				Validators.required
			])),
			email: new FormControl('', Validators.compose([
				Validators.required
			])),
			content: new FormControl('', Validators.compose([
				Validators.required
			])),
		});
	}

* 2. app/form/form.page.html へ記述

(お名前フォームのみ)複数入力フォームがある場合は適宜追加すること

<form [formGroup]="loginForm">
    <ion-item>
        <ion-label position="stacked">お名前 <ion-text color="danger">*</ion-text></ion-label>
        <ion-input type="text" formControlName="username"></ion-input>

        <!-- error message -->
        <div class="error-container">
            <ng-container *ngFor="let validation of validations.username">
                <div class="error-message"
                    *ngIf="loginForm.get('username').hasError(validation.type) && (loginForm.get('username').dirty || loginForm.get('username').touched)">
                    <ion-icon name="information-circle-outline" color="danger"></ion-icon>
                    <ion-text color="danger">{{ validation.message }}</ion-text>
                </div>
            </ng-container>
        </div>
        <!-- /error message -->

    </ion-item>

	<div class="ion-padding">
		<ion-button [disabled]="!loginForm.valid" (click)="onClickSubmit()" expand="block" type="submit"
			class="ion-no-margin">送信する</ion-button>
	</div>

</form>

参考 : http://bit.ly/2RkXiXS

No.1680
01/24 19:17

edit