i have custom angular validator defined as below
import { Validator, AbstractControl, NG_VALIDATORS } from '@angular/forms';
import { Directive, Input } from '@angular/core';
@Directive({
selector: '[ecMinVal]',
providers: [
{
provide: NG_VALIDATORS,
useExisting: ecMinVal,
multi: true
}]
})
export class ecMinVal implements Validator {
@Input() ecMinVal = 0;
validate(control: AbstractControl): { [key: string]: any } | null {
return Number(control.value) < this.ecMinVal ? { 'lessThanMinVal': true } : null;
}
}
I am using it in number textbox component like this
<div >
<input type="number"
#txtBoxNumber="ngModel"
[ecMinVal]="ecMinVal1"
[(ngModel)]="value"
(focus)="onFocus($event)"
(ngModelChange)="change($event)"
onkeydown="if(event.key==='.' || event.key==='e' || event.key==='E'){event.preventDefault();}"
ng-required="required">
<div *ngIf="txtBoxNumber.errors?.['lessThanMinVal'] " >
<span>
Value should be greater than or equal to {{ecMinVal1}}
</span>
</div>
</div>
I want user to see the validation Value should be greater than or equal to {{ecMinVal1}} . This works fine when user changes value and the value is less than the value of variable ecMinVal1
However i want user to see this message when component finished loading in their browser and even if the user has not changed anything.
Not sure why the txtBoxNumber.errors is null on component load and is populated when user changes value.
CodePudding user response:
because by default value is null and in validator you are converting the value
- Number(null) which yields 0, 0 < 0 is false
- Number(undefined) which yields NaN, NaN < 0 is false.
You can add some check before
validate(control: AbstractControl): { [key: string]: any } | null {
const value = control.value;
if (typeof value === 'undefined' || value === null) {
return { lessThanMinVal: true };
}
return Number(value) < this.ecMinVal ? { lessThanMinVal: true } : null;
}