验证器与表单中的其他值相同 [英] Validators same as other value in form

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

问题描述

我想知道是否有一个验证器可以比较来自同一表单的两个不同值 - 假设我有以下内容:

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]
  });

我在文档中找到了this,但是它不是很有帮助.

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}));   <--------

这样您就可以访问组的所有控件,而不仅仅是一个... 这可以使用组控件的 controls 属性访问.后者(不是单个)在触发验证时直接提供.例如:

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:

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆