-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmin-value-validator.directive.ts
37 lines (29 loc) · 1.17 KB
/
min-value-validator.directive.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import { Directive, Input, forwardRef, OnChanges, SimpleChanges } from '@angular/core';
import { AbstractControl, NG_VALIDATORS, Validator } from '@angular/forms';
@Directive({
selector: '[minvalue]',
providers: [
{ provide: NG_VALIDATORS, useExisting: forwardRef(() => MinValueValidator), multi: true }
],
host: { '[attr.min]': 'minValue' }
})
export class MinValueValidator implements Validator, OnChanges {
@Input('minvalue') minValue: number;
registerOnValidatorChange(fn: () => void): void { this._onChange = fn; }
private _onChange: () => void;
ngOnChanges(changes: SimpleChanges): void {
if ('minValue' in changes) {
if (this._onChange) this._onChange();
}
}
validate(control: AbstractControl): { [key: string]: any } {
const givenvalue = control.value;
let validationResult = null;
const minValue = this.minValue;
if (minValue && givenvalue < minValue) {
validationResult = validationResult || {};
validationResult = { minvalue: { requiredValue: this.minValue } };
}
return validationResult;
}
}