我正在尝试编写一个自定义密码匹配验证器,当我输入两个不同的密码时,我在控制台中收到了 TypeError。我正在使用 Angular Material 控件并使用类进行验证。如果可能,我想避免使用 ReactiveForms 和 FormGroup。我一直在尝试几种方法,但无法使确认密码方法起作用。任何帮助将不胜感激!谢谢!
打字稿:
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from "@angular/forms";
import { Router } from '@angular/router';
@Component({
templateUrl: './password-reset.component.html',
styleUrls: ['./password-reset.component.css']
})
export class PasswordResetComponent {
hide = true;
imageSrc = '../../assets/images/logo.png';
password = new FormControl('', [Validators.required,
Validators.minLength(8)]);
confirm_password = new FormControl('', [Validators.required,
Validators.minLength(8)], this.passwordMatchValidator);
passwordMatchValidator(FormControl) {
return this.password.value !== this.confirm_password.value
? null : { 'mismatch': true };
}
getPasswordErrorMessage() {
return this.password.hasError('required') ? 'Please enter a password'
:
this.password.hasError('minlength') ? 'Password must be at least 8
characters' :
'';
}
getConfirmPasswordErrorMessage() {
return this.confirm_password.hasError('required') ? 'Please enter a
password' :
this.confirm_password.hasError('minlength') ? 'Password must be at
least 8 characters' :
this.confirm_password.hasError(this.passwordMatchValidator) ?
'Passwords must match' :
'';
}
}
HTML:
<div class="form-group">
<mat-form-field class="justifier">
<input matInput placeholder="Password" [formControl]="password" [type]="hide ? 'password' : 'text'" required>
<mat-error *ngIf="password.invalid && (password.dirty || password.touched)">{{getPasswordErrorMessage()}}</mat-error>
<mat-icon class="pw mat-icon2" matSuffix (click)="hide = !hide">{{hide ? 'visibility_off' : 'visibility'}}</mat-icon>
</mat-form-field>
</div>
<div class="form-group">
<mat-form-field class="justifier">
<input matInput placeholder="Confirm Password" [formControl]="confirm_password" [type]="hide ? 'password' : 'text'" required>
<mat-error *ngIf="confirm_password.invalid || password.value !== confirm_password.value || (confirm_password.dirty || confirm_password.touched)">{{getConfirmPasswordErrorMessage()}}</mat-error>
<!--<mat-error *ngIf=" password.value !== confirm_password.value">both passwords must match!</mat-error>-->
<mat-icon class="pw mat-icon2" matSuffix (click)="hide = !hide">{{hide ? 'visibility_off' : 'visibility'}}</mat-icon>
</mat-form-field>
</div>
此处的错误意味着未定义的“this”。尝试创建函数的绑定版本。
this.passwordMatchValidator.bind(this)
这里的问题是该函数不会立即调用,而是作为 angular 调用验证器时的回调,因此“this”上下文丢失了。.bind 确保它按您的预期工作。欲了解更多信息,请https://github.com/Microsoft/TypeScript/wiki/ 'this'-in-TypeScript
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句