微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – Angular 2:向ngModelGroup添加验证器

我正在使用ngModelGroup指令将多个表单输入组合在一起.

在文档(https://angular.io/docs/ts/latest/api/forms/index/NgModelGroup-directive.html)中,我读到有一个验证器:任何[]属性.

这是否意味着我可以添加一个自定义验证器函数,该函数仅验证该ngModelGroup?如果是这样,我该如何使用它?

这将是非常棒的,因为我想检查是否至少检查了ngModelGroup中的一个复选框.我无法使用必需,因为这意味着所有复选框都是必需的.我在文档中找不到任何相关内容,或者我找错了地方?

解决方法:

这完全可以使用ngModelGroup和用于验证的自定义指令.了解其工作原理的关键是ngModelGroup

Creates and binds a FormGroup instance to a DOM element.

首先,我们将构建我们的指令,这个指令非常简单,没有什么特别的东西:

@Directive({
  selector: '[hasrequiredCheckBoxInGroup]',
  providers: [{provide: NG_VALIDATORS, useExisting: HasrequiredCheckBoxInGroup, multi: true}]
})
export class HasrequiredCheckBoxInGroup implements Validator, OnChanges {
  private valFn = Validators.nullValidator;

  constructor() {
    this.valFn = validaterequiredCheckBoxInGroup();
  }

  validate(control: AbstractControl): {[key: string]: any} {
    return this.valFn(control);
  }
}

我们的验证功能是我们掌握ngModelGroup创建FormGroup并应用它的关键知识的地方:

function validaterequiredCheckBoxInGroup() : ValidatorFn {
      return (group) => { //take the group we declare in the template as a parameter
        let isValid = false; //default to invalid for this case
        if(group) {
          for(let ctrl in group.controls) {
            if(group.controls[ctrl].value && typeof group.controls[ctrl].value === 'boolean') { // including a radio button set might blow this up, but hey, let's be careful with the directives
              isValid = group.controls[ctrl].value;
            }
          }
        }

        if(isValid) {
          return null;
        } else {
          return { checkBoxrequired: true };
        }
      }
    }

最后,在我们的模块中包含并声明了指令,我们返回到模板(需要在一个表单中):

<form #f="ngForm">
      <div ngModelGroup="checkBoxes" #chks="ngModelGroup" hasrequiredCheckBoxInGroup>
          <input type="checkBox" name="chk1" [(ngModel)]="checks['1']"/>
          <input type="checkBox" name="chk2" [(ngModel)]="checks['2']"/>
      </div>
      <div>
      {{chks.valid}}
      </div>
</form>

这里有一个可以玩的所有玩具:
http://plnkr.co/edit/AXWGn5XwRo60fkqGBU3V?p=preview

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐