-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmax-value-validator.directive.ts
37 lines (29 loc) · 1.17 KB
/
max-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: '[maxvalue]',
providers: [
{ provide: NG_VALIDATORS, useExisting: forwardRef(() => MaxValueValidator), multi: true }
],
host: { '[attr.max]': 'maxValue' }
})
export class MaxValueValidator implements Validator, OnChanges {
@Input('maxvalue') maxValue: number;
registerOnValidatorChange(fn: () => void): void { this._onChange = fn; }
private _onChange: () => void;
ngOnChanges(changes: SimpleChanges): void {
if ('maxValue' in changes) {
if (this._onChange) this._onChange();
}
}
validate(control: AbstractControl): { [key: string]: any } {
const givenvalue = control.value;
let validationResult = null;
const maxValue = this.maxValue;
if (maxValue && givenvalue > maxValue) {
validationResult = validationResult || {};
validationResult = { maxvalue: { requiredValue: this.maxValue }};
}
return validationResult;
}
}