【发布时间】:2019-08-21 11:07:16
【问题描述】:
我正在创建一个表单来创建一个新用户。我正在使用自定义验证器来验证密码和确认密码字段值是否匹配。我已将这两个字段设为必填,即它们不能为空。如果密码字段为空并且我尝试创建用户,则会显示错误。但是,当确认密码字段为空时不会引发错误。如果确认密码字段为空,我仍然无法创建用户,但我希望显示错误。我不知道该怎么办。请帮忙。提前致谢。
这是我的模板:
<mat-form-field class="login-field-full-width margin">
<input matInput [type]="!hidePassword ? 'password' : 'text'" formControlName="password" placeholder="Password" name="password" class="form-control" id="password">
<mat-error *ngIf="addForm.controls.password.hasError('required')">Password is required</mat-error>
</mat-form-field>
<mat-form-field class="login-field-full-width">
<input matInput formControlName="passwordAgain" placeholder="Confirm password" [type]="!hideConfirmPassword ? 'password' : 'text'" [errorStateMatcher]="passwordsMatcher">
<mat-error *ngIf="addForm.controls.passwordAgain.hasError('required')">Confirm Password is required</mat-error><mat-error *ngIf="addForm.hasError('passwordsNotEqual')">Password Mismatch!</mat-error>
</mat-form-field>
我的自定义 errorStateMatcher:
export class RepeatPasswordEStateMatcher implements ErrorStateMatcher {
isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
return (control && control.parent.get('password').value !== control.parent.get('passwordAgain').value && control.dirty);
}
}
export function RepeatPasswordValidator(group: FormGroup) {
const password = group.controls.password.value;
const passwordConfirmation = group.controls.passwordAgain.value;
return password === passwordConfirmation ? null : { passwordsNotEqual: true };
}
我的表单组:
passwordsMatcher = new RepeatPasswordEStateMatcher;
this.addForm = this.formBuilder.group({
id: [],
username: ['', Validators.required],
password: new FormControl('', [Validators.required]),
passwordAgain: new FormControl('', [Validators.required]),
}, { validator: RepeatPasswordValidator });
}
onSubmit() {
if (this.addForm.valid) {
this.userService.createUser( this.addForm.value)
.subscribe();
}
}
【问题讨论】:
-
在这段代码中,当确认密码字段为空时,我无法收到错误消息。
-
好吧,我刚刚告诉过你,我试过你的代码,它可以工作。请在 stackblitz 中复制该问题 :)
-
当您将确认密码字段留空时,您是否能够收到密码要求错误
-
是的。因此,我要求演示 :) 它适用于 Angular 版本 8,我可以确认。
-
奇怪。我无法得到那个错误。
标签: html angular typescript validation