需要Angular 2条件验证器吗? [英] Angular 2 conditional Validators.required?

查看:55
本文介绍了需要Angular 2条件验证器吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应该如何有条件地要求一个表单字段?我做了一个自定义验证器,但是传递给该自定义验证器的条件变量是静态的,并保持其初始值.我的自定义验证器应该如何获取更新的条件值?也许有一种方法可以用Validators.required代替自定义验证器?

How should I go about conditionally requiring a form field? I made a custom validator, but the conditional variables that I pass to the custom validator are static and remain their initial values. What should my custom validator look like to get updated conditional values? Perhaps there is a way to do this with Validators.required instead of a custom validator?

private foo: boolean = false;
private bar: boolean = true;

constructor(private _fb: FormBuilder) {
    function conditionalRequired(...conditions: boolean[]) {
      return (control: Control): { [s: string]: boolean } => {
        let required: boolean = true;
        for (var i = 0; i < conditions.length; i++) {
          if (conditions[i] === false) {
            required = false;
          }
        }
        if (required && !control.value) {
          return { required: true }
        }
      }
    }
    this.applyForm = _fb.group({
          'firstName': ['', Validators.compose([
            conditionalRequired(this.foo, !this.bar)
          ])],
          ...
    });
}

更新(2016年5月17日)

已经发布了很长时间,但是我想引用ControlGroup类上提供的.include().exclude()方法,供那些尝试创建此功能的人使用. ( docs )虽然可能存在用例对于上面的条件验证器,我发现控件,控件组和控件数组的包含和排除是处理此问题的好方法.只需在您想要的控件上设置required验证器,然后根据需要包含/排除它即可.希望这对某人有帮助!

It's been a long time since posting this, but I'd like to reference the .include() and .exclude() methods available on the ControlGroup class for anyone out there who is trying to create this functionality. (docs) While there are probably use cases for a conditional Validator like above, I've found the inclusion and exclusion of controls, control groups, and control arrays to be a great way to handle this. Just set the required validator on the control you'd like and include/exclude it as you please. Hope this helps someone!

推荐答案

在您发表评论之后,我看到了一个潜在的问题.由于您将条件作为原始类型提供给创建验证器函数的函数,因此将使用调用第一个函数时的值.即使之后更改,也不会考虑新值.

Following your comment I can see a potential problem. Since you provide conditions as primitive types to the function that creates the validators function, the values when calling the first one will be used. Even if they change after, the new values won't be taken into account.

要存档,您需要将对象用于如下所述的条件:

To archive that you need to use an object for conditions as described below:

private foo: boolean = false;
private bar: boolean = true;

private conditions: any = {
  condition1: foo,
  condition2: !bar
};

constructor(private _fb: FormBuilder) {
    function conditionalRequired(conditions: any) {
      return (control: Control): { [s: string]: boolean } => {
        let required: boolean = true;
        for (var elt in conditions) {
          var condition = conditions[elt];
          if (conditions === false) {
            required = false;
          }
        }
        if (required && !control.value) {
          return { required: true };
        }
      }
    }
    this.applyForm = _fb.group({
          'firstName': ['', Validators.compose([
            conditionalRequired(conditions)
          ])],
          ...
    });
}

这样,可以通过引用使用/更新conditions参数.要更新您的条件,您需要执行以下操作:

This way the conditions parameter can be used / updated by reference. To update your conditions, you need to do the following:

updateConditions() {
  this.conditions.condition1 = true;
  this.conditions.condition2 = true;
}

这是一个unk客: https://plnkr.co/edit/bnX7p0?p=preview .

修改

要在更新条件时运行验证器,需要显式调用控件的updateValueAndValidity方法.在这种情况下,控件和表单的valid属性都将相应更新:

To run the validator when updating the conditions, you need to explicitly call the updateValueAndValidity method of the control. In this case, the valid attribute of both control and form will be updated accordingly:

updateConditions() {
  this.conditions.condition1 = true;
  this.conditions.condition2 = true;
  this.applyForm.controls.firstName.updateValueAndValidity();
}

这篇关于需要Angular 2条件验证器吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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