在 Angular 6 中确认密码验证 [英] Confirm password validation in Angular 6

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

问题描述

我想仅使用材料组件执行密码确认密码验证,并在确认密码下方显示错误消息字段如果确认密码字段不匹配如果为空.尝试了很多资源都无法实现.

也试过

<块引用>

HTML

 <input matInput placeholder="新密码" [type]="隐藏 ? '密码': 'text'" [formControl]="passFormControl" required><mat-icon matSuffix (click)="hide = !hide">{{hide ?可见性":'visibility_off'}}</mat-icon><mat-error *ngIf="passFormControl.hasError('required')">请输入您的新密码</mat-error></mat-form-field><mat-form-field ><input matInput placeholder="确认密码" [type]="隐藏 ?'密码':'文本'" [formControl]="confirmFormControl"需要><mat-icon matSuffix (click)="hide = !hide">{{hide ?可见性":'visibility_off'}}</mat-icon><mat-error *ngIf="confirmFormControl.hasError('required')">确认你的密码</mat-error></mat-form-field>

<块引用>

TS

 import {Component, OnInit } from '@angular/core';导入 {FormControl, FormGroupDirective, NgForm, Validators} from'@角度/表格';从@angular/material/core"导入{ErrorStateMatcher};@成分({选择器:'asd-set-pass',templateUrl: './set-pass.component.html',styleUrls: ['./set-pass.component.css']})passFormControl = new FormControl('', [Validators.required,]);ConfirmFormControl = new FormControl('', [Validators.required,]);隐藏=真;}

它可以很好地验证以下条件1)如果密码和确认密码字段为空,则显示错误文本.

我想与 (.ts) 文件中的字段进行比较,例如它如何验证空字段,如果确认密码字段为空,则会出现错误.

解决方案

这个问题可以结合这两个答案来解决:https://stackoverflow.com/a/43493648/6294072https://stackoverflow.com/a/47670892/6294072

因此,首先,您需要一个自定义验证器来检查密码,它可能如下所示:

checkPasswords: ValidatorFn = (group: AbstractControl): ValidationErrors |空 =>{let pass = group.get('password').value;让confirmPass = group.get('confirmPassword').value返回通行证 === 确认通行证?空:{不相同:真实}}

并且您将为您的字段创建一个表单组,而不仅仅是两个表单控件,然后为您的表单组标记该自定义验证器:

this.myForm = this.fb.group({密码:['', [Validators.required]],确认密码: ['']}, { 验证器:this.checkPasswords })

然后如其他答案中所述,mat-error 仅显示 FormControl 是否无效,因此您需要一个错误状态匹配器:

导出类 MyErrorStateMatcher 实现 ErrorStateMatcher {isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {const invalidCtrl = !!(control?.invalid && control?.parent?.dirty);const invalidParent = !!(control?.parent?.invalid && control?.parent?.dirty);返回无效Ctrl ||无效的父母;}}

在上面,您可以调整何时显示错误消息.我只会在触摸 password 字段时显示消息.另外我想在上面,从 confirmPassword 字段中删除 required 验证器,因为如果密码不匹配,表单无论如何都是无效的.

然后在组件中新建一个ErrorStateMatcher:

matcher = new MyErrorStateMatcher();

最后,模板将如下所示:

<mat-form-field><input matInput placeholder="新密码";formControlName=密码"需要><mat-error *ngIf="myForm.hasError('required', 'password')">请输入您的新密码</mat-error></mat-form-field><mat-form-field><input matInput placeholder="确认密码";formControlName=确认密码";[errorStateMatcher]=匹配器"><mat-error *ngIf="myForm.hasError('notSame')">密码不匹配</mat-error></mat-form-field></表单>

以下是使用上述代码的演示:StackBlitz

I want to perform password and confirm password validations using material components only,and an error message below the confirm password field if confirm password field doesn't match And if it is empty.Tried many resources unable to achieve.

Tried this video too.

This is the material component i am looking for

HTML

     <mat-form-field >
        <input matInput  placeholder="New password" [type]="hide ? 'password' 
          : 'text'" [formControl]="passFormControl" required>
        <mat-icon matSuffix (click)="hide = !hide">{{hide ? 'visibility' : 
          'visibility_off'}}</mat-icon>
        <mat-error *ngIf="passFormControl.hasError('required')">
            Please enter your newpassword
         </mat-error>
      </mat-form-field>

      <mat-form-field >
         <input matInput  placeholder="Confirm password" [type]="hide ? 
              'password' : 'text'" [formControl]="confirmFormControl" 
                    required>
         <mat-icon matSuffix (click)="hide = !hide">{{hide ? 'visibility' : 
                'visibility_off'}}</mat-icon>
         <mat-error *ngIf="confirmFormControl.hasError('required')">
          Confirm your password
          </mat-error>
      </mat-form-field>

TS

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

     @Component({
            selector: 'asd-set-pass',
            templateUrl: './set-pass.component.html',
             styleUrls: ['./set-pass.component.css']
         })

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

             hide =true;

       }

It's validating the following conditions fine 1)If password and confirm password fields are empty its showing error text.

I want to compare to fields in (.ts) file like how its validating for empty field, and an error to come if confirm password field is empty.

解决方案

This question could be solved with a combination of these two answers: https://stackoverflow.com/a/43493648/6294072 and https://stackoverflow.com/a/47670892/6294072

So first of all, you would need a custom validator for checking the passwords, that could look like this:

checkPasswords: ValidatorFn = (group: AbstractControl):  ValidationErrors | null => { 
  let pass = group.get('password').value;
  let confirmPass = group.get('confirmPassword').value
  return pass === confirmPass ? null : { notSame: true }
}

and you would create a formgroup for your fields, instead of just two form controls, then mark that custom validator for your form group:

this.myForm = this.fb.group({
  password: ['', [Validators.required]],
  confirmPassword: ['']
}, { validators: this.checkPasswords })

and then as mentioned in other answer, the mat-error only shows if a FormControl is invalid, so you need an error state matcher:

export class MyErrorStateMatcher implements ErrorStateMatcher {
  isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
    const invalidCtrl = !!(control?.invalid && control?.parent?.dirty);
    const invalidParent = !!(control?.parent?.invalid && control?.parent?.dirty);

    return invalidCtrl || invalidParent;
  }
}

in the above you can tweak when to show error message. I would only show message when the password field is touched. Also I would like above, remove the required validator from the confirmPassword field, since the form is not valid anyway if passwords do not match.

Then in component, create a new ErrorStateMatcher:

matcher = new MyErrorStateMatcher();

Finally, the template would look like this:

<form [formGroup]="myForm">
  <mat-form-field>
    <input matInput placeholder="New password" formControlName="password" required>
    <mat-error *ngIf="myForm.hasError('required', 'password')">
      Please enter your new password
    </mat-error>
  </mat-form-field>

  <mat-form-field>
    <input matInput placeholder="Confirm password" formControlName="confirmPassword" [errorStateMatcher]="matcher">
    <mat-error *ngIf="myForm.hasError('notSame')">
      Passwords do not match
    </mat-error>  
  </mat-form-field>
</form>

Here's a demo for you with the above code: StackBlitz

这篇关于在 Angular 6 中确认密码验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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