import {Directive, Input} from '@angular/core'; import {AbstractControl, NG_VALIDATORS} from '@angular/forms'; import {ValidationService} from './services/validation.service'; @Directive({ selector: '[appValidate]', providers: [{provide: NG_VALIDATORS, useExisting: ValidateDirective, multi: true}] }) export class ValidateDirective { @Input('appValidate') method: string; @Input('appValidateArgs') args: Array; constructor( private validation: ValidationService ) { } validate(control: AbstractControl): {[key: string]: any} | null { let ok; let error; if (this.args) { ({ok, error} = this.validation[this.method](control.value, ...this.args)); } else { ({ok, error} = this.validation[this.method](control.value)); } return ok ? null : { failure: error }; } }