【发布时间】:2018-04-30 21:38:42
【问题描述】:
我正在尝试编写自定义密码匹配验证器,当我输入两个不同的密码时,控制台中出现 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>
【问题讨论】:
标签: angular typescript