首页 > 解决方案 > 验证器需要不与自定义验证器一起使用

问题描述

我正在创建一个表单来创建一个新用户。我正在使用自定义验证器来验证密码和确认密码字段值是否匹配。我已将这两个字段设为必填,即它们不能为空。如果密码字段为空并且我尝试创建用户,则会显示错误。但是,当确认密码字段为空时不会引发错误。如果确认密码字段为空,我仍然无法创建用户,但我希望显示错误。我不知道该怎么办。请帮忙。提前致谢。

这是我的模板:

<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();

    }

  }

标签: htmlangulartypescriptvalidation

解决方案


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


推荐阅读