This question has already been answered. I'd like to extend the answer from @amd. Sometimes you might need a default value.
For example, to validate against a specific value, I'd like to provide it as follows-
<input integerMinValue="20" >
But the minimum value of a 32 bit signed integer is -2147483648. To validate against this value, I don't like to provide it. I'd like to write as follows-
<input integerMinValue >
To achieve this you can write your directive as follows
import {Directive, Input} from '@angular/core';
import {AbstractControl, NG_VALIDATORS, ValidationErrors, Validator, Validators} from '@angular/forms';
@Directive({
selector: '[integerMinValue]',
providers: [{provide: NG_VALIDATORS, useExisting: IntegerMinValidatorDirective, multi: true}]
})
export class IntegerMinValidatorDirective implements Validator {
private minValue = -2147483648;
@Input('integerMinValue') set min(value: number) {
if (value) {
this.minValue = +value;
}
}
validate(control: AbstractControl): ValidationErrors | null {
return Validators.min(this.minValue)(control);
}
}