Angular 2:向ngModelGroup添加验证器

Joh*_*han 4 javascript validation angular2-forms angular

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

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

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

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

sil*_*sod 8

这完全可以使用a ngModelGroup和custom指令进行验证.了解其工作原理的关键在于此ngModelGroup

创建FormGroup实例并将其绑定到DOM元素.

首先,我们将构建我们的指令,这是一个非常模板化的东西:

@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);
  }
}
Run Code Online (Sandbox Code Playgroud)

我们的验证功能是我们掌握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 };
        }
      }
    }
Run Code Online (Sandbox Code Playgroud)

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

<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>
Run Code Online (Sandbox Code Playgroud)

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