260a93edbc72cdb1c2bac3c75569d33c03804c0a
[sdc/sdc-workflow-designer.git] /
1 import {AfterViewInit, Directive, ElementRef, forwardRef, Input} from '@angular/core';
2 import {AbstractControl, NG_VALIDATORS, ValidatorFn, Validators} from '@angular/forms';
3
4 import {NumberWrapperParseFloat} from '../core/number-wrapper-parse';
5
6 @Directive({
7   selector: '[min][ngModel],[min][formControl],[min][formControlName]',
8   providers: [{
9         provide: NG_VALIDATORS,
10         useExisting: forwardRef(() => MinValidatorDirective),
11         multi: true
12   }],
13 })
14
15 export class MinValidatorDirective implements AfterViewInit {
16   private _validator: ValidatorFn;
17   private inputElement: any;
18   constructor(elementRef: ElementRef) {
19         this.inputElement = elementRef;
20   }
21   ngAfterViewInit() {
22         this.inputElement = this.inputElement.nativeElement.querySelector('input');
23         if (this.inputElement && this.inputElement.querySelector('input')) {
24                 this._validator = min(NumberWrapperParseFloat(
25                         this.inputElement.querySelector('input').getAttribute('min')));
26         }
27   }
28   @Input()
29   set min(minValue: string) {
30         this._validator = min(NumberWrapperParseFloat(minValue));
31   }
32
33   validate(c: AbstractControl): {[key: string]: any} {
34         return this._validator(c);
35   }
36 }
37
38 function min(minvalue: number): ValidatorFn {
39   return (control: AbstractControl): {[key: string]: any} => {
40         if (Validators.required(control) !== undefined &&
41                 Validators.required(control) !== null) {
42                 return null;
43         }
44         let v: Number = Number(control.value);
45         return v < minvalue ?
46                 {'min': {'requiredValue': minvalue, 'actualValue': v}} :
47                 null;
48   };
49 }