Validators same as other value in form

2019-06-07 23:27发布

I am wondering if there is a Validator that compares two different values from the same form - lets say I have the following:

 this.loginForm = fb.group({
      email: ["", Validators.required],
      password: ["", Validators.required],
      repeatPassword: ["", Validators.required]
  });

I found this in documentation, however it wasn't very helpful.

Any ideas?

1条回答
淡お忘
2楼-- · 2019-06-07 23:55

You need to assign a validator to a complete form group to implement this. Something like that:

this.form = fb.group({
  name: ['', Validators.required],
  email: ['', Validators.required]
  matchingPassword: fb.group({
    password: ['', Validators.required],
    repeatPassword: ['', Validators.required]
  }
}, {validator: this.areEqual}));   <--------

This way you will have access to all controls of the group and not only one... This can be accessed using the controls property of the group control. The latter (not a single one) is directly provided when validation is triggered. For example:

areEqual(group: ControlGroup) {
  var valid = false;

  for (name in group.controls) {
    var val = group.controls[name].value

    (...)
  }

  if (valid) {
    return null;
  }

  return {
    areEqual: true
  };
}

See this question for more details:

查看更多
登录 后发表回答