I wrote a custom validator for Reactive forms in Angular 2.But my function is validating only first key press in the text field. Here my custom function supposed to validate each key press. Could any one please correct me.
This is the way I am calling custom function in my class.
'customerNumberOwner': new FormControl('', [CustomValidators.CustomerNumberCustomValidation(6,8)]),
Here is my custom function.
//Custom validator for Customer number owner
static CustomerNumberCustomValidation(min: number, max: number): ValidatorFn {
return (c: AbstractControl): { [key: string]: boolean } | null => {
var reg=/[^A-Za-z0-9]+/;
if(c && (c.value !== '')){
const str=c.value;
if (str.match(reg) || str.length<min ||str.length>max ){
console.log('Invalid')
return {
'CustomerNumberCustomValidation' : true
};
}
}
return null;
};
}
I hope this will help
DEMO
HTML:
app.component.ts:
custom-validator.service.ts: