【问题标题】:reactive forms equal password validations反应形式等同于密码验证
【发布时间】:2021-10-19 19:36:43
【问题描述】:

只有在 signupForm 有效的情况下才会启用注册按钮,但现在我有一个问题,即使密码和确认密码不匹配,该按钮也会启用

是我的 this.equalWithPasswordValidator。执行错误?

有什么想法吗?谢谢。

#html代码

 <button mat-raised-button class="full-width v-btn-lrg mt-0px" color="primary" type="submit"
            [disabled]="signupForm.invalid">
            {{labels.BUTTON.SETUP}}
          </button>

#ts 代码

    this.signupForm = this.fb.group({
      confirmPassword: [
        '',
        [Validators.required, this.equalWithPasswordValidator.bind(this)],
        
      ],
      password: [
        '',
        [
          this.validatePasswordRequired,
          this.validateMinimumPassword,
          this.validatePasswordUpperCase,
          this.validatePasswordLowerCase,
          this.validatePasswordSpecialCharacter,
          this.validateOneNumber,
        ],
      ],
    });
  }

  equalWithPasswordValidator(): ValidatorFn {
    return (control: AbstractControl): ValidationErrors | null => {
      const equal = control.value === this.signupForm.get('password').value;
      return equal ? { notEqual: { value: 'Passwords do not match' } } : null;
    };
  }

【问题讨论】:

标签: angular typescript


【解决方案1】:

您需要对 FormGroup 应用验证器,以便您可以访问这两个控件。这是创建验证器以比较两个字段的一种方法...

  // component

  form = new FormGroup({
    password: new FormControl('', [ yourValidators... ]),
    confirmPassword: new FormControl('', [ yourValidators... ])
  }, {
    validators: [ equivalentValidator('password', 'confirmPassword') ]
  });


  // equivalent.validator.ts

  import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';
    
  export const equivalentValidator = (firstControlName: string, secondControlName: string): ValidatorFn => {
    
    return (control: AbstractControl): ValidationErrors | null => {
      const firstControl = control.get(firstControlName);
      const secondControl = control.get(secondControlName);
    
      if (secondControl.value && secondControl.value !== firstControl.value) {
        secondControl.setErrors({ notEqual: true });
      }
    
      return null;
    };
    
  };

在本例中,如果第二个字段与第一个字段不匹配,我只会在第二个字段上设置错误。我没有在此处设置错误消息,而是设置了notEqual 的错误,以便可以跨表单重复使用验证器。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-15
    • 2021-01-14
    • 2019-05-12
    • 2021-01-11
    • 1970-01-01
    • 2017-11-22
    • 1970-01-01
    • 2020-10-17
    相关资源
    最近更新 更多