I am currently working on an Angular form implementation that allows users to enter their phone numbers. I have integrated a custom directive called appPhoneExtMask for formatting the phone numbers and have also implemented Angular form validation for both minlength and maxlength. However, I am facing an issue where the input field triggers a validation error if the user only inputs spaces. I would like the form to either ignore or trim any spaces before conducting the validation checks. Below is the snippet of code pertaining to the input field:
My expectation is to receive only numerical input, disregard any string values, and ensure that the length falls within the specified minimum and maximum range.
import {
Directive,
HostListener
} from '@angular/core';
import {
NgControl,
Validators
} from '@angular/forms';
@Directive({
selector: '[formControlName][appPhoneExtMask]',
})
export class PhoneExtentionMaskDirective {
constructor(public ngControl: NgControl) {}
@HostListener('ngModelChange', ['$event'])
onModelChange(event) {
this.onInputChange(event, false);
}
@HostListener('keydown.backspace', ['$event'])
keydownBackspace(event) {
this.onInputChange(this.ngControl.control.value, true);
}
ngOnInit() {
this.formatValue(this.ngControl.control.value, false);
}
onInputChange(event, backspace) {
this.formatValue(event, backspace);
}
formatValue(event, backspace) {
if (event === null) {
return;
}
let newVal = event.replace(/\D/g, '');
if (backspace && newVal.length <= 6) {
newVal = newVal.substring(0, newVal.length - 1);
}
// Remaining code block unchanged for brevity...
<input type="text" placeholder="Phone" class="form-control" formControlName="phone" minlength="12" maxlength="20" appPhoneExtMask [ngClass]="{ 'is-invalid': (isSaved && contactForm.get('phone').errors)}">