在 Angular Reactive Form - FormBuilder 中检查相同的密码并确认密码

Check for same password and confirm password in Angular Reactive Form - FormBuilder

我正在尝试使用 .NET Core 创建 Angular5 注册表单。

我正在检查注册表中的密码和重新输入的密码是否相同。我正在使用 FormBuilder 作为表单。

但是检查 password1 和 password2 总是失败。我也试过===

if (this.RegistrationForm.valid) {
  if (this.RegistrationForm.get('password1') == this.RegistrationForm.get('password2')) {
    this.MyService.Register(this.RegistrationForm.value).subscribe((data) => {}, error => this.errorMessage = error)
  } else {
    this.errorMessage = "cdscs";
  }
}

constructor(private fb: FormBuilder, private MyService: RoadSignService) {
        this.RegistrationForm = this.fb.group({
            Id: 0,
            name: ['', [Validators.required]],
            email: ['', [Validators.required]],
            gender: ['', [Validators.required]],
            department: ['', [Validators.required]],
            address: ['', [Validators.required]],
            password1: ['', [Validators.required]],
            password2: ['', [Validators.required]]
        })
    }

您的用户提交表单后,表单值将在 this.RegistrationForm.value 中作为 JSON 对象提供。所以你可以用它来进行比较。

只需使用this.RegistrationForm.value.password1 === this.RegistrationForm.value.password2

if (this.RegistrationForm.valid) {
  if (this.RegistrationForm..value.password1 === this.RegistrationForm.value.password2) {
    this.MyService.Register(this.RegistrationForm.value)
      .subscribe(
        (data) => {}, 
        error => this.errorMessage = error
      )
  } else {
    this.errorMessage = "cdscs";
  }
}

PS: 如果您想创建一个执行此操作的自定义验证器,.

我会将其作为整个 FormGroup 的验证器来处理,而不是提交表单,然后进行检查。

当您定义 FormGroup 时,您可以为整个组添加一个验证器,这样您就可以访问所有 controls/values:

validatePasswords(formGroup: FormGroup): any {
    const password = formGroup.controls['password'];
    const confirmPassword = formGroup.controls['confirmPassword'];

    // don't validate
    if (password.pristine || confirmPassword.pristine) {
      return null;
    }

    formGroup.markAsTouched();

    if (password.value === confirmPassword.value) {
      return null;
    }

    return confirmPassword.setErrors({
      notEqual: true
    });
  }

form = this.formBuilder.group({
  . . .,
  password: [
    '', [
      Validators.required,
      Validators.pattern(regexPatterns.password),
    ]
  ],
  confirmPassword: [
    '', [
      Validators.required,
      Validators.pattern(regexPatterns.password)
    ]
  ]
}, {
  validator: this.validatePasswords
});

在本例中,regexPatterns.password只是RegExp对象的共享导入,表达式为:/^(?=.{8,})(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&+=*]).*/

现在,您可以在 提交表单并调用任何其他逻辑、API 调用或任何昂贵的操作之前 向用户显示这两个字段是否匹配。

我想这里最好的方法是添加一个自定义验证器来比较两个密码,例如:

// Custom validator
function validateRePassword(control: FormControl){
  const { root } = control;
  const pass = root.get('password'),
        rePass = root.get('rePassword');

  if(!pass || !rePass) {
    return null;
  }

  const passVal = pass.value,
        rePassVal = rePass.value;

  const result = passVal===rePassVal ? null : { passDontMatch: true };
  return result;
}

// Form initialization
this.formGroup = fb.group({
      user: fb.control('UserName'),
      password: fb.control(''),
      rePassword: fb.control('', [validateRePassword])
    })

// function to check if the control has the 'passDontMatch' error and therefore display some related message
passMatch(){
    return !this.formGroup.get('rePassword').hasError('passDontMatch');
  }

自定义验证器对我不起作用,即使使用自定义状态匹配器也是如此。

我正在用手检查密码。

<input type="password" formControlName="password" (input)="checkPasswordsMatch()">
<input type="password" formControlName="confirmPassword" (input)="checkPasswordsMatch()">
<p class="error" *ngIf="form.get('confirmPassword').hasError('notSame')"> It works </p>
checkPasswordsMatch(): void {
  const password = this.form.get('password');
  const confirmPassword = this.form.get('confirmPassword');

  if (password.value !== confirmPassword.value) {
    this.form.get('confirmPassword').setErrors({ notSame: true });
  }
}