本文介绍了验证器相同的形式其它的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如果存在两个不同的值从相同的形式对比了验证 - 可以说我有以下几点:

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.

任何想法?

推荐答案

您需要验证程序分配到一个完整的表单组来实现这一点。这样的事情:

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

这篇关于验证器相同的形式其它的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 17:16