角度6中的表单验证

时间:2018-08-01 05:52:15

标签: angular angular6 angular-forms

下面是我的组件文件(login.component.html)

   <form >
      <div id="login-container"  [class.mat-elevation-z12]="!isActive"
        [class.mat-elevation-z8]="isActive">

        <h2>Login</h2>

        <mat-form-field class="example-full-width">
          <input matInput placeholder="Email address" 
               [formControl]="emailFormControl" required>
          <mat-error *ngIf="emailFormControl.hasError('required')">
            Please enter email id
          </mat-error>
        </mat-form-field>

        <mat-form-field >
            <input matInput  placeholder="Password" minlength="6" 
               maxlength="15"  [type]="hide ? 'password' : 'text'" 
                 [formControl]="passFormControl" required>
             <mat-error *ngIf="passFormControl.hasError('required')">
                Please enter password
             </mat-error>
             <mat-error *ngIf="!minlength">
                Password must be 6-15 characters long
             </mat-error>
         </mat-form-field>

        <mat-slide-toggle color="primary"><span class="toggle-btn">Remember 
         me</span></mat-slide-toggle>

      <div> 
          <a [routerLink]="['../signup']"><button mat-raised-button 
            class="Sign-Up-btn">Sign Up</button></a>
          <a [routerLink]="['../']"><button mat-raised-button color="primary" 
           class="Login-btn" >Login</button></a>
      </div> 
      <div class="footer-sec">
          <br><br>
          <a [routerLink]="['../forgot-pass']">Forgot Password?</a><br><br>
          <mat-divider></mat-divider>
      </div>   
    </div>
<form >

(login.component.ts)文件

   import { Component, OnInit } from '@angular/core';
   import {FormControl, FormGroupDirective, NgForm, Validators} from 
      '@angular/forms';
   import {ErrorStateMatcher} from '@angular/material/core';

   @Component({
     selector: 'ylb-login',
     templateUrl: './login.component.html',
     styleUrls: ['./login.component.css']
   })
   export class LoginComponent {

   emailFormControl = new FormControl('', [
    Validators.required,
   ]);

    passFormControl = new FormControl('', [
      Validators.required,
    ]);
    hide =true;//password hiding

    }

输入和密码组件都可以正常工作,并使用

显示正确的错误消息
    <mat-error>,

现在,如果我单击所需的登录/注册消息,则必须输入错误消息

     <mat-error>.

我该如何实现?阅读许多完全困惑的文章。

1 个答案:

答案 0 :(得分:1)

看看下面的代码

login.component.html

<form novalidate [formGroup]="loginForm">
  <div id="login-container" [class.mat-elevation-z12]="!isActive" [class.mat-elevation-z8]="isActive">

    <h2>Login</h2>

    <mat-form-field class="example-full-width">
      <input matInput placeholder="Email address" formControlName="email" required>
      <mat-error *ngIf="loginForm.controls.email.hasError('required')">
        Please enter email id
      </mat-error>
    </mat-form-field>

    <mat-form-field>
      <input matInput placeholder="Password" minlength="6" maxlength="15" [type]="hide ? 'password' : 'text'" formControlName="password"
        required>
      <mat-error *ngIf="loginForm.controls.password.hasError('required')">
        Please enter password
      </mat-error>
      <mat-error *ngIf="loginForm.controls.password.hasError('minlength')">
        Password must be 6-15 characters long
      </mat-error>
    </mat-form-field>

    <mat-slide-toggle color="primary">
      <span class="toggle-btn">Remember me
      </span>
    </mat-slide-toggle>

    <div>
      <button mat-raised-button class="Sign-Up-btn" (click)="onSignup()">Sign Up</button>
      <button mat-raised-button color="primary" class="Login-btn" (click)="onLogin()">Login</button>
    </div>

    <div class="footer-sec">
      <br>
      <br>
      <a [routerLink]="['../forgot-pass']">Forgot Password?</a>
      <br>
      <br>
      <mat-divider></mat-divider>
      <p>Powered by yletlabs pvt ltd</p>
    </div>
  </div>
</form>

login.component.ts

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';
import { Router } from '@angular/router';
import { ValidatorUtil } from '../utils/validator.util';

@Component({
  selector: 'ylb-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  loginForm: FormGroup;
  signupForm: FormGroup;
  hide = true; //password hiding

  constructor(private fb: FormBuilder,
              private router: Router) { }

  ngOnInit() {
    this.loginForm = this.fb.group({
      'email': [null, [Validators.required]],
      'password': [null, [Validators.required, Validators.minLength(6)]]
    });

    this.signupForm = this.fb.group({
      'email': [null, [Validators.required]],
      'password': [null, [Validators.required, Validators.minLength(6)]],
      'confirmPassword': [null, [Validators.required, ValidatorUtil.matchWithValidator('password')]],
    });
  }

  onLogin() {
    this._markAsDirty(this.loginForm);

    // add login logic here...
    //this.router.navigate(['/home']);
  }

  onSignup() {
    this._markAsDirty(this.loginForm);

    // add signup logic here...
    //this.router.navigate(['/signup']);
  }

  private _markAsDirty(group: FormGroup) {
    group.markAsDirty();
    for (let i in group.controls) {
      group.controls[i].markAsDirty();
    }
  }

}

validator.util.ts

import {FormControl} from "@angular/forms";

export class ValidatorUtil {

  public static matchWithValidator(toControlName: string) {
    let ctrl: FormControl;
    let toCtrl: FormControl;
    return function matchWith(control: FormControl): {[key: string]: any} {

      if (!control.parent) {
        return null;
      }

      if (!ctrl) {
        ctrl = control;
        toCtrl = control.parent.get(toControlName) as FormControl;

        if (!toCtrl) {
          return null;
        }

        toCtrl.valueChanges.subscribe(() => {
          ctrl.updateValueAndValidity();
        });
      }

      if (ctrl.value !== "" && toCtrl.value !== ctrl.value) {
        return {
          matchWith: true
        }
      }
      return null;
    }
  }
}