angular 8:反应式匹配密码

hos*_*ein 3 validation angular angular-reactive-forms

我的 angular 项目中有反应形式,它定义如下:

this.createUserFormGroup = new FormGroup({
  'userName': new FormControl(null, [Validators.required, Validators.maxLength(256)]),
  'name': new FormControl(null, [Validators.required, Validators.maxLength(64)]),
  'roleNames': new FormArray([]),
  'password': new FormControl(null, [Validators.required, Validators.maxLength(32)]),
  'confirmPassword': new FormControl(null, [Validators.required])
});
Run Code Online (Sandbox Code Playgroud)

如何检查密码和确认密码的匹配?

Dha*_*tel 9

您可以创建自定义验证器并在 FormGroup 中使用它,例如

    passwordConfirming(c: AbstractControl): { invalid: boolean } {
    if (c.get('password').value !== c.get('confirmPassword').value) {
        return {invalid: true};
    }
}
Run Code Online (Sandbox Code Playgroud)

你需要像这样使用这个自定义验证器。

 this.createUserFormGroup = new FormGroup({
  'userName': new FormControl(null, [Validators.required, Validators.maxLength(256)]),
  'name': new FormControl(null, [Validators.required, Validators.maxLength(64)]),
  'roleNames': new FormArray([]),
  'password': new FormControl(null, [Validators.required, Validators.maxLength(32)]),
  'confirmPassword': new FormControl(null, [Validators.required])
},{validator: this.passwordConfirming});
Run Code Online (Sandbox Code Playgroud)

并检查 html 就像

 <span *ngIf="createUserFormGroup.errors?.invalid">
      Password doesn't match
  </span>
Run Code Online (Sandbox Code Playgroud)