开发者问题收集

自定义验证器用于检查 Angular 6 和 Reactive Form 中的密码是否匹配

2019-01-26
974

我有一个包含 4 个输入字段的表单,其中 2 个用于输入电子邮件,2 个用于输入密码。我想检查电子邮件和密码是否匹配。我在表单组中使用验证器。

accountInformation: FormGroup;

constructor(private fb: FormBuilder) {
    this.accountInformation = this.fb.group({
      emailAddress: [null, Validators.compose([Validators.required, Validators.email])],
      emailAddressConfirmed: [null, Validators.compose([Validators.required, Validators.email])],
      password: [null, Validators.compose([Validators.required, Validators.minLength(6)])],
      passwordConfirmed: [null, Validators.compose([Validators.required, Validators.minLength(6)])],
    }, {validator: this.matchValidator});
  }

matchValidator(form: FormGroup) {
    const passwordInput = form['value'];
    if (passwordInput.password === passwordInput.passwordConfirmed) {
      // These ones gives me errors in console
      this.removeError(this.accountInformation.get('password'), 'mismatch');
      // this.removeError(this.accountInformation.controls, 'mismatch');

      // If I do these...
      // form.controls['password'].setErrors(null);
      // form.controls['passwordConfirmed'].setErrors(null);
      // This will remove all errors of all types
    } else {
      form.controls['password'].setErrors({'mismatch': true});
      form.controls['passwordConfirmed'].setErrors({'mismatch': true});
    }
  }

  removeError(control: AbstractControl, error: string) {
    const err = control.errors; // get control errors
    if (err) {
      delete err[error]; // delete your own error
      if (!Object.keys(err).length) { // if no errors left
        control.setErrors(null); // set control errors to null making it VALID
      } else {
        control.setErrors(err); // controls got other errors so set them back
      }
    }
  }

我在控制台中收到此错误:

Error: Uncaught (in promise): TypeError: Cannot read property 'get' of
undefined TypeError: Cannot read property 'get' of undefined
    at FormGroup.push../src/app/components/register/register.component.ts.RegisterComponent.matchValidator
[as validator]

在这些字段中,我还有 requiredminlength ,如果我执行 setErrors(null) ,我不想丢失它们。另外,我也不知道如何检查电子邮件。也许我把代码弄得太复杂了。

2个回答

仅当错误数组中没有其他错误时,您才需要将错误设置为 null。例如,您可以检查长度。

Константин Носов
2019-01-26

您可以在获取表单控件的值之前尝试进行空值检查,如下所示;

matchValidator(control: AbstractControl) {
    const password: string = control.get('password').value; // get password from our password form control
    const passwordConfirmed: string = control.get('passwordConfirmed').value; // get password from our passwordConfirmed form control
    // compare is the password math
    if (password !== passwordConfirmed) {
        // if they don't match, set an error in our passwordConfirmed form control
        control.get('passwordConfirmed').setErrors({ mismatch: true });
    }
  }
Kıvanç B.
2019-01-26