我正在创建一个表单来创建一个新用户。我正在使用自定义验证程序来验证密码并确认密码字段值是否匹配。我已经将两个字段都设为必填字段,即它们不能为空。如果密码字段为空并且我尝试创建用户,则会显示错误。但是当确认密码字段为空时不会引发任何错误。如果确认密码字段为空,我仍然无法创建用户,但我希望显示错误。我不知道该怎么办。请帮忙。预先感谢。
这是我的模板
<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 };
}
我的formGroup:
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();
}
}
答案 0 :(得分:0)
在错误状态匹配器中,您可以收听form.submitted
并显示是否已提交表单的验证。
可能您不想同时显示必需的消息和自定义的错误消息,因此请添加对自定义验证模板的检查:
*ngIf="addForm.hasError('passwordsNotEqual') &&
!addForm.hasError('required', 'passwordAgain')"
然后如上所述,在自定义错误状态匹配器中添加检查表单form.submitted
:
return ((control && form.form.get('password').value !== control.value && control.dirty)
|| form.submitted)
演示:StackBlitz