Find the custom validator for min number validation. The selector name of our directive is customMin.
custom-min-validator.directive.ts
import { Directive, Input } from '@angular/core';
import { NG_VALIDATORS, Validator, FormControl } from '@angular/forms';
@Directive({
selector: '[customMin][formControlName],[customMin][formControl],[customMin][ngModel]',
providers: [{provide: NG_VALIDATORS, useExisting: CustomMinDirective, multi: true}]
})
export class CustomMinDirective implements Validator {
@Input()
customMin: number;
validate(c: FormControl): {[key: string]: any} {
let v = c.value;
return ( v < this.customMin)? {"customMin": true} : null;
}
}
Find the custom validator for max number validation. The selector name of our directive is customMax.
custom-max-validator.directive.ts
import { Directive, Input } from '@angular/core';
import { NG_VALIDATORS, Validator, FormControl } from '@angular/forms';
@Directive({
selector: '[customMax][formControlName],[customMax][formControl],[customMax][ngModel]',
providers: [{provide: NG_VALIDATORS, useExisting: CustomMaxDirective, multi: true}]
})
export class CustomMaxDirective implements Validator {
@Input()
customMax: number;
validate(c: FormControl): {[key: string]: any} {
let v = c.value;
return ( v > this.customMax)? {"customMax": true} : null;
}
}
We can use customMax with formControlName, formControl and ngModel attributes.
Using Custom Min and Max Validator in Template-driven Form
We will use our custom min and max validator in template-driven form. For min number validation we have customMin attribute and for max number validation we have customMax attribute. Now find the code snippet for validation.
<input name="num1" [ngModel]="user.num1" customMin="15" #numberOne="ngModel">
<input name="num2" [ngModel]="user.num2" customMax="50" #numberTwo="ngModel">
We can show validation error messages as following.
<div *ngIf="numberOne.errors?.customMin">
Minimum required number is 15.
</div>
<div *ngIf="numberTwo.errors?.customMax">
Maximum number can be 50.
</div>
To assign min and max number we can also use property biding. Suppose we have following component properties.
minNum = 15;
maxNum = 50;
Now use property binding for customMin and customMax as following.
<input name="num1" [ngModel]="user.num1" [customMin]="minNum" #numberOne="ngModel">
<input name="num2" [ngModel]="user.num2" [customMax]="maxNum" #numberTwo="ngModel">