I'm currently working on implementing a validation rule for phone numbers in the form I'm designing. I've decided to utilize the ng2-tel-input library, even though my form is built using Angular 6.
However, I've encountered an issue where I am unable to display an error message when the phone number input is invalid.
Below is the snippet of my HTML code:
<input class="form-control phoneField"
ng2TelInput
(hasError)="hasError($event)"
(intlTelInputObject)="telInputObject($event)"
type="text" pattern="^[\s0-9]*$" [required]="emailReq ? false :
!null" [(ngModel)]="phoneReq"
name="phone" #phone="ngModel" phoneValidator style="width: 100%
!important">
Typescript code section
import * as ngTelInput from 'ng2-tel-input';
import 'intl-tel-input';
import 'intl-tel-input/build/js/utils';
export class phoneValidator {
@Input('ng2TelInputOptions') ng2TelInputOptions: any;
@Output('hasError') hasError: EventEmitter<boolean> = new EventEmitter();
@Output('ng2TelOutput') ng2TelOutput: EventEmitter<any> = new EventEmitter();
@Output('intlTelInputObject') intlTelInputObject: EventEmitter<any> = new
EventEmitter(); ngTelInput: any;
constructor (private el: ElementRef) {}
@HostListener('blur') onBlur() {
let isInputValid:boolean = this.isInputValid();
if (isInputValid) {
let telOutput = this.ngTelInput.intlTelInput("getNumber");
this.hasError.emit(isInputValid);
this.ng2TelOutput.emit(telOutput);
} else
{
this.hasError.emit(isInputValid);
}
}
isInputValid(): boolean {
return this.ngTelInput.intlTelInput('isValidNumber') ? true : false;
}
}
As a newcomer to Angular, I am struggling to understand why it is not functioning correctly.
I attempted to test the hasError function with the following code:
hasError(obj) {
console.log('hasError: ', obj);
}
It seems to be working fine, displaying 'true' for valid phone numbers and 'false' for invalid ones. However, the form does not detect an invalid number or show an error message accordingly.
If anyone can provide some guidance on this issue, I would greatly appreciate it.