I'm trying to use google-libphonenumber's AsYouTypeFormatter
with a simple input element on a web form. I pass each key typed by the user to the inputDigit
method. The problem I'm running into is that when the user hits backspace, google-libphonenumber doesn't remove the last digit and simply appends Backspace
to the phone number. Am I using the AsYouTypeFormatter improperly? Is it not able to deal with backspaces? If so, and I suspect that is the case, how should I handle the case where the user presses backspace?
Here is a link to an example project: https://stackblitz.com/edit/libphonenumber
And here is the code:
import { AsYouTypeFormatter } from 'google-libphonenumber';
const appDiv: HTMLElement = document.getElementById('app');
appDiv.innerHTML = `
<h1>Libphonenumber Playground</h1>
<input id="input" type="text">
`;
this.formatter = new AsYouTypeFormatter('us');
const input = document.getElementById('input') as HTMLInputElement;
input.addEventListener('keyup', (event: KeyboardEvent) => {
console.log(this.formatter.inputDigit(event.key));
});
"isNumber": function(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if ((charCode > 31 && (charCode < 48 || charCode > 57) || charCode === 46 || charCode === 13)) {
//do not allow non numeric characters
evt.preventDefault();
}else{
//ok: numeric character
//handle phone number masking.
this.phoneNumberForm =this.formatter.inputDigit(evt.key);
}
I haven't found any methods that will move the formatter index back. (That doesn't mean that they are not there) What I did was prevent the backspace keydown event. Along with any other non-numeric character. Here is the function I used: