Angular 2中的条件必需验证程序指令

时间:2016-05-02 15:42:00

标签: validation typescript angular angular2-directives

我需要根据其他字段的值来确定是否需要某些表单字段。内置的RequiredValidator指令似乎不支持这个,所以我创建了自己的指令:

@Directive({
  selector: '[myRequired][ngControl]',
  providers: [new Provider(NG_VALIDATORS, { useExisting: forwardRef(() => MyRequiredValidator), multi: true })]
})
class MyRequiredValidator {
  @Input('myRequired') required: boolean;

  validate(control: AbstractControl): { [key: string]: any } {
    return this.required && !control.value
      ? { myRequired: true }
      : null;
  }
}

样本用法:

<form>
  <p><label><input type="checkbox" [(ngModel)]="isNameRequired"> Is Name Required?</label></p>
  <p><label>Name: <input type="text" [myRequired]="isNameRequired" #nameControl="ngForm" ngControl="name" [(ngModel)]="name"></label></p>
  <p *ngIf="nameControl.control?.hasError('myRequired')">This field is required.</p>
</form>

如果用户首先切换复选框,然后在文本框中键入或删除文本,则此方法可以正常工作。但是,如果用户在文本框为空白时切换复选框,则验证消息不会正确更新。

如何修改MyRequiredValidator以在其required属性发生更改时触发验证?

注意:我正在寻找仅涉及MyRequiredValidator更改的解决方案。我想避免向App组件添加任何逻辑。

Plunker:https://plnkr.co/edit/ExBdzh6nVHrcm51rQ5Fi?p=preview

1 个答案:

答案 0 :(得分:3)

我会使用类似的东西:

@Directive({
  selector: '[myRequired][ngControl]',
  providers: [new Provider(NG_VALIDATORS, { useExisting: forwardRef(() => MyRequiredValidator), multi: true })]
})
class MyRequiredValidator {
  @Input('myRequired') required: boolean;

  ngOnChanges() {
    // Called when required is updated
    if (this.control) {
      this.control.updateValueAndValidity();
    }
  }

  validate(control: AbstractControl): { [key: string]: any } {
    this.control = control;
    return this.required && !control.value
      ? { myRequired: true }
      : null;
  }
}

请参阅此plunkr:https://plnkr.co/edit/14jDdUj1rdzAaLEBaB9G?p=preview