2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

angularでのバリデーション実装方法

Posted at

はじめに

Angularを使用していて、バリデーションをするときに手こずったので、自分用と同じ問題で困っている人のために実装方法を記録しておきたいと思います。

実装例

<form #loginForm="ngForm" novalidate>
  <label for="mail-address">メールアドレス</label>
  <input id="mail-address" type="email" name="mail"
    [(ngModel)]="login.mail" #mail="ngModel" required email/>
  <div *ngIf="mail.errors && (mail.dirty || mail.touched)"
    class="alert alert-danger">
    <div [hidden]="!mail.errors.required">
      入力してください
    </div>
  </div>
</form>
import { Component, OnInit } from '@angular/core';

@Component({
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss'],
})
export class LoginComponent implements OnInit {
  login = {
    mail: '',
    password: ''
  };
  constructor() {}

  ngOnInit() {
  }
}

注意点

以下処理を入れないと、ページ表示時にもバリデーションが働いてしまうので注意する必要がある。

*ngIf="mail.errors && (mail.dirty || mail.touched)"

参考

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?