FormBuilder 中调用方法的多个验证器

Multiple validator for call method in FormBuilder

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

passwordemail 的第二个字段中,我想检查第一个是否与第二个相同。

如果我只检查一个,passwordemail,它有效,但对两者都无效...

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,但这不是我的问题。感谢您的帮助

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

正确的语法应该是

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>

See sample on stackblitz