1

我创建了一个注册表单。密码电子邮件两个字段。

在此处输入图像描述

密码电子邮件的第二个字段中,我想检查第一个字段是否与第二个字段相同。

如果我只检查一个密码电子邮件,它可以工作,但对于两者都不起作用......

this.registerForm = this.formBuilder.group({
      email: '', [Validators.required, Validators.email],
      confirmEmail: '', [Validators.required],
      password: '', [Validators.required],
      confirmPassword: '', [Validators.required],
    }, {
      validator: matchingFields('password', 'confirmPassword')
    });

如何添加第二个validator

this.registerForm = this.formBuilder.group({
      email: '', [Validators.required, Validators.email],
      confirmEmail: '', [Validators.required],
      password: '', [Validators.required],
      confirmPassword: '', [Validators.required],
    }, {
      validator: matchingFields('password', 'confirmPassword'),
      // this doesn't work
      validator: matchingFields('email', 'confirmEmail')
    });

那么方法(matchingFields)对于密码电子邮件是相同的:

function matchingFields(field1, field2) {
  return form => {
    if (form.controls[field1].value !== form.controls[field2].value) {
      return {mismatchedFields: true};
    }
  };
}

我找不到任何解决方案validator,仅适用于Validators.required,但这不是我的问题。感谢您的帮助

4

1 回答 1

0

您用于生成表单组的语法不正确

正确的语法应该是

this.fb.group({
    control: ['value', [Validator1, Validator2, ...]]
})

在你的情况下,这看起来像

function confirmed(field: string) {
  const confirmField = 'confirm' + field.replace(/(^|\s)\S/g, t => t.toUpperCase() );
  return form => {
    if (form.get(field).value !== form.get(confirmField).value) {
      return { ['mismatched-' + field]: true };
    }
  };
}

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  constructor(private formBuilder: FormBuilder) {}
  name = "Angular " + VERSION.major;
  registerForm = this.formBuilder.group(
    {
      email: ["myEmail@yahoo.com", [Validators.required, Validators.email]],
      confirmEmail: ["myEmail@yahoo.com", [Validators.required]],
      password: ["Password@1", [Validators.required]],
      confirmPassword: ["Password@1", [Validators.required]]
    },
    {
      validators: [confirmed("password"),confirmed("email")]
    }
  );
}

示例 HTML

<hello name="{{ name }}"></hello>
<form [formGroup]='registerForm'>
    <input formControlName='email'> {{ registerForm.get('email').status}} <br>
    <input formControlName='confirmEmail'> {{ registerForm.get('confirmEmail').status}} <br>
    <input formControlName='password'> {{ registerForm.get('password').status}}<br>
    <input formControlName='confirmPassword'> {{ registerForm.get('confirmPassword').status}}<br>
</form>

    Password Confirmed Error: <strong>{{ registerForm.getError('mismatched-password')}}</strong> <br>
Email Confirmed: <strong>{{ registerForm.getError('mismatched-email')}}</strong>

    <h1>{{ registerForm.status }}</h1>

请参阅 stackblitz 上的示例

于 2020-10-22T19:54:54.520 回答