I have a following validation directive:
import { Directive, Input } from '@angular/core';
import { Validator, ValidationErrors, AbstractControl, NG_VALIDATORS } from '@angular/forms';
import { isNumber } from 'util';
@Directive({
selector: '[minMaxValidator]',
providers: [{
provide: NG_VALIDATORS,
useExisting: MinMaxValidatorDirective,
multi: true
}]
})
export class MinMaxValidatorDirective implements Validator {
@Input() public minValue: number = null;
@Input() public maxValue: number = null;
constructor() { }
validate(c: AbstractControl): ValidationErrors {
let result: ValidationErrors = null;
if (isNumber(c.value)) {
if (this.minValue !== null && this.minValue > c.value) {
result = { message: 'Value must be greater than ' + this.minValue };
}
if (this.maxValue !== null && this.maxValue < c.value) {
result = { message: 'Value must be lower than ' + this.maxValue };
}
}
return result;
}
}
And I use it like this:
<input type="text" min-max-validator minValue="0" maxValue="1" [(ngModel)]="data.compression" />
Input renders, but validate method in validator is never called. I have no errors in console and validator is registered in app.module.ts
What am I missing?
You should be using minMaxValidator
(the selector for your directive) on your input field.
<input type="text" minMaxValidator minValue="0" maxValue="1" [(ngModel)]="data.compression" />