角度6中的表单验证 [英] Form validation in angular 6

查看:58
本文介绍了角度6中的表单验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Below is my component file(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)文件

(login.component.ts)file

   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

    }

两个输入&密码组件工作正常,并使用

Both input & password components are working fine and displaying proper error messages using

    <mat-error>,

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

Now if i click on login/signup required error messages has to come in

     <mat-error>.

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

How can i achieve this?Read many articles fully confused.

推荐答案

看看下面的代码

login.component.html

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

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

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;
    }
  }
}

这篇关于角度6中的表单验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆