【问题标题】:Check for same password and confirm password in Angular Reactive Form - FormBuilder在 Angular Reactive Form - FormBuilder 中检查相同的密码并确认密码
【发布时间】:2018-10-14 15:19:51
【问题描述】:

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

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

但是检查密码 1 和密码 2 总是失败。我也试过===

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]]
        })
    }

【问题讨论】:

  • 我试过了。但没有任何帮助
  • console.log(this.RegistrationForm.get('password1'), this.RegistrationForm.get('password2')); 并在此处发布结果。
  • 你需要先用console.log 调试,做那行,检查有什么问题,可能是多余的空间。 console.log(this.RegistrationForm.get('password1'), this.RegistrationForm.get('password2'), this.RegistrationForm.get('password1') == this.RegistrationForm.get('password2'))
  • 你能发布你的 HTML 和 formbuilder 代码吗?

标签: angular typescript angular-formbuilder


【解决方案1】:

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

当您定义 FormGroup 时,您可以为整个组添加一个验证器,从而使您能够访问所有控件/值:

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 调用或任何昂贵的操作之前向用户显示这两个字段是否匹配

【讨论】:

    【解决方案2】:

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

    // 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');
      }
    

    【讨论】:

      【解决方案3】:

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

      我正在用手检查密码。

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

      【讨论】:

        【解决方案4】:

        一旦您的用户提交表单,表单值将在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:如果您想创建一个执行此操作的自定义验证器,please refer to this OP

        【讨论】:

        • 我用过 get password1() { return this.RegistrationForm.value.password1; }。相比之下@SiddAjmera 是否有问题
        猜你喜欢
        • 1970-01-01
        • 2023-03-25
        • 2017-05-13
        • 2018-12-25
        • 2019-04-12
        • 2015-04-03
        • 2023-02-23
        • 1970-01-01
        • 2015-05-18
        相关资源
        最近更新 更多