Validators same as other value in form

时间秒杀一切 提交于 2019-12-08 06:45:48

问题


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:


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:

  • Angular2 validator which relies on multiple form fields


来源:https://stackoverflow.com/questions/36064513/validators-same-as-other-value-in-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!