143dccc6d4f8bc9782bf76dfe6003298ec602180
[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: '[max][ngModel],[max][formControl],[max][formControlName]',
8   providers: [{
9         provide: NG_VALIDATORS,
10         useExisting: forwardRef(() => MaxValidatorDirective),
11         multi: true
12   }],
13 })
14
15 export class MaxValidatorDirective 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 = max(NumberWrapperParseFloat(
25                         this.inputElement.querySelector('input').getAttribute('max')));
26         }
27   }
28   @Input()
29   set max(maxValue: string) {
30         this._validator = max(NumberWrapperParseFloat(maxValue));
31   }
32
33   validate(c: AbstractControl): {[key: string]: any} {
34         return this._validator(c);
35   }
36 }
37
38 function max(maxvalue: 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 > maxvalue ?
46                 {'max': {'requiredValue': maxvalue, 'actualValue': v}} :
47                 null;
48   };
49 }