使用[(ngModel)]时显示验证错误消息

时间:2018-10-11 09:17:41

标签: angular angularjs-directive

如果使用模式的验证不匹配,我正在使用[(ngModel)]显示消息,但无法显示错误消息。有两种验证方式,一种是针对字段的验证,另一种针对模式错误的验证。一个错误正在显示,这是必需的,而另一个错误则是在模式错误时不显示的。预先感谢您分享您的知识。

// login.html

 <div class="app-body">
  <main class="main d-flex align-items-center">
    <div class="container">
      <div class="row">
        <div class="col-md-8 mx-auto">
          <div class="card-group">
            <div class="card p-4">
              <div class="card-body">
                <!-- <form (ngSubmit)="onSubmit(f.value)" #f=ngForm> -->
                <form #form="ngForm">
                  <h1>Login</h1>
                  <p class="text-muted">Sign In to your account</p>
                  <div class="input-group mb-3" [ngClass]="{'has-error': (!username.valid && username.touched), 'has-success': (username.valid && username.touched)}">
                    <div class="input-group-prepend">
                      <span class="input-group-text"><i class="icon-user"></i></span>
                    </div>
                    <input type="email" class="form-control" [(ngModel)]="user.username" placeholder="Username"
                      autocomplete="username" ngModel #username="ngModel" name="username" required>
                    <div *ngIf="username.errors?.required && (username.dirty || username.touched)" class="help-block" style="color: #813838">
                      Email is required!
                      <div *ngIf="username.errors?.pattern" class="help-block" style="color: #813838">
                          pattern is required!
                        </div>
                    </div>

                  </div>  
                  <div class="input-group mb-4" [ngClass]="{'has-error': (!password.valid && password.touched), 'has-success': (password.valid && password.touched)}">
                    <div class="input-group-prepend">
                      <span class="input-group-text"><i class="icon-lock"></i></span>
                    </div>
                    <input type="password" [(ngModel)]="user.password" class="form-control" placeholder="Password"
                      autocomplete="current-password" #password="ngModel" ngModel name="password" required>
                    <div *ngIf="password.invalid && (password.dirty || password.touched)" class="help-block" style="color: #813838">
                      Password is required!
                    </div>  
                  </div>
                  <div class="row">
                    <div class="col-6">
                      <button type="submit" [disabled]="!form.valid" class="btn btn-primary px-4" (click)="onSubmit()">Login</button>
                    </div>
                    <div class="col-6 text-right">
                      <button type="button" class="btn btn-link px-0">Forgot password?</button>
                    </div>
                  </div>
                </form>
              </div>
            </div>
            <div class="card text-white bg-primary py-5 d-md-down-none" style="width:44%">
              <div class="card-body text-center">
                <div>
                  <h2>Sign up</h2>
                  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut
                    labore et dolore magna aliqua.</p>
                  <button type="button" class="btn btn-primary active mt-3">Register Now!</button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </main>
</div>

// login.ts

import { Component, OnInit } from '@angular/core';
import { NgForm, FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms';
import { getLocaleTimeFormat } from '@angular/common';
import { Router } from '@angular/router';

@Component({
  selector: 'app-dashboard',
  templateUrl: 'login.component.html'
})
export class LoginComponent implements OnInit {
  // regexEmail = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  regexEmail = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  user: any = {};
  pass: any = {};
  form: FormGroup;
  constructor(private router: Router, private formBuilder: FormBuilder
    ) {

  }
ngOnInit() {
    this.form = new FormGroup({
      'username': new FormControl("", [Validators.required, Validators.pattern(this.regexEmail)]),
      'password': new FormControl("", [Validators.required])
    });
  }
onSubmit() {
    console.log(this.user.username);
    console.log(this.form.value);
this.user = this.form.value.username !== null ? this.user = this.loginForm.value.username : this.user = "";
    this.pass = this.form.value.password !== null ? this.pass = this.loginForm.value.password : this.pass = "";
    if (this.user === localStorage.getItem('username') && this.pass === localStorage.getItem('password')) {
      this.router.navigate(['/dashboard']);
      alert("LOG IN SUCCESS!");
    }
    else {
      this.onValidate();
      alert("Username and Password did not match!");
      this.loginForm.reset();
      // this.onValidate()
    }
 }
}

2 个答案:

答案 0 :(得分:0)

在输入字段中进行更改:

 <div class="input-group mb-3" [ngClass]="{'has-error': (!username.valid && username.touched), 'has-success': (username.valid && username.touched)}">
 <div class="input-group-prepend">
    <span class="input-group-text"><i class="icon-user"></i> 
    </span>
</div>
<input name="username" type="email" class="control-label" [(ngModel)]="user.username" placeholder="Username" autocomplete="username" #username="ngModel" required />
<div *ngIf="username.invalid && username.errors.required && (username.dirty || username.touched)" class="help-block" style="color: #813838">Email is required!</div>

有关更多详细信息,您可以阅读官方文档Form Validation

答案 1 :(得分:0)

对于电子邮件验证,您需要添加另一个<div>来消除这种令人讨厌的模式错误:

<div *ngIf="username.invalid && username.errors.pattern && (username.dirty || username.touched)" class="help-block" style="color: #813838">Email is Not Vliad!</div>