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

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

问题描述

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

 
<div id="登录容器" [class.mat-elevation-z12]="!isActive"[class.mat-elevation-z8]="isActive"><h2>登录</h2><mat-form-field class="example-full-width"><input matInput placeholder="电子邮件地址"[formControl]="emailFormControl" required><mat-error *ngIf="emailFormControl.hasError('required')">请输入电子邮件ID</mat-error></mat-form-field><mat-form-field ><input matInput placeholder="密码" minlength="6"maxlength="15" [type]="hide ? 'password' : 'text'"[formControl]="passFormControl" required><mat-error *ngIf="passFormControl.hasError('required')">请输入密码</mat-error><mat-error *ngIf="!minlength">密码长度必须为 6-15 个字符</mat-error></mat-form-field><mat-slide-toggle color="primary"><span class="toggle-btn">记住我</span></mat-slide-toggle><div><a [routerLink]="['../signup']"><button mat-raised-buttonclass="Sign-Up-btn">注册</button></a><a [routerLink]="['../']"><button mat-raised-button color="primary"class="登录-btn" >登录</button></a>

<div class="footer-sec"><br><br><a [routerLink]="['../forgot-pass']">忘记密码?</a><br><br><mat-divider></mat-divider>

<表格>

(login.component.ts)文件

 import { Component, OnInit } from '@angular/core';导入 {FormControl, FormGroupDirective, NgForm, Validators} from'@角度/表格';从@angular/material/core"导入{ErrorStateMatcher};@成分({选择器:'ylb-login',templateUrl: './login.component.html',styleUrls: ['./login.component.css']})导出类 LoginComponent {emailFormControl = new FormControl('', [Validators.required,]);passFormControl = new FormControl('', [Validators.required,]);hide =true;//密码隐藏}

输入和密码组件工作正常并使用

显示正确的错误消息

 ,

现在如果我点击登录/注册所需的错误消息必须进来

 .

我怎样才能做到这一点?阅读许多完全困惑的文章.

解决方案

看下面的代码

login.component.html

<div id="login-container" [class.mat-elevation-z12]="!isActive" [class.mat-elevation-z8]="isActive"><h2>登录</h2><mat-form-field class="example-full-width"><input matInput placeholder="Email address" formControlName="email" required><mat-error *ngIf="loginForm.controls.email.hasError('required')">请输入电子邮件ID</mat-error></mat-form-field><mat-form-field><input matInput placeholder="Password" minlength="6" maxlength="15" [type]="hide ? 'password' : 'text'" formControlName="password"需要><mat-error *ngIf="loginForm.controls.password.hasError('required')">请输入密码</mat-error><mat-error *ngIf="loginForm.controls.password.hasError('minlength')">密码长度必须为 6-15 个字符</mat-error></mat-form-field><mat-slide-toggle color="primary"><span class="toggle-btn">记住我</span></mat-slide-toggle><div><button mat-raised-button class="Sign-Up-btn" (click)="onSignup()">注册</button><button mat-raised-button color="primary" class="Login-btn" (click)="onLogin()">登录</button>

<div class="footer-sec"><br><br><a [routerLink]="['../forgot-pass']">忘记密码?</a><br><br><mat-divider></mat-divider><p>由 yletlabs pvt ltd</p> 提供支持

</表单>

登录.component.ts

import { Component, OnInit } from '@angular/core';从@angular/forms"导入 { FormBuilder, FormGroup, Validators, FormControl };从@angular/router"导入{路由器};从'../utils/validator.util'导入{ValidatorUtil};@成分({选择器:'ylb-login',templateUrl: './login.component.html',styleUrls: ['./login.component.css']})导出类 LoginComponent 实现 OnInit {登录表单:表单组;注册表格:表格组;隐藏=真;//密码隐藏构造函数(私人FB:FormBuilder,私有路由器:路由器) { }ngOnInit() {this.loginForm = this.fb.group({'email': [null, [Validators.required]],'密码': [null, [Validators.required, Validators.minLength(6)]]});this.signupForm = this.fb.group({'email': [null, [Validators.required]],'密码': [null, [Validators.required, Validators.minLength(6)]],'confirmPassword': [null, [Validators.required, ValidatorUtil.matchWithValidator('password')]],});}登录(){this._markAsDirty(this.loginForm);//在这里添加登录逻辑...//this.router.navigate(['/home']);}注册(){this._markAsDirty(this.loginForm);//在这里添加注册逻辑...//this.router.navigate(['/signup']);}私人_markAsDirty(组:FormGroup){group.markAsDirty();对于(让我在 group.controls 中){group.controls[i].markAsDirty();}}}

validator.util.ts

从@angular/forms"导入{FormControl};导出类 ValidatorUtil {公共静态 matchWithValidator(toControlName: string) {让 ctrl: FormControl;让 toCtrl: FormControl;返回函数 matchWith(control: FormControl): {[key: string]: any} {如果 (!control.parent) {返回空;}如果(!ctrl){ctrl = 控制;toCtrl = control.parent.get(toControlName) as FormControl;如果(!toCtrl){返回空;}toCtrl.valueChanges.subscribe(() => {ctrl.updateValueAndValidity();});}if (ctrl.value !== "" && toCtrl.value !== ctrl.value) {返回 {匹配:真}}返回空;}}}

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)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.

解决方案

Take a look at code below

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

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

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆