Home > Software design >  Formatting input field phone number with EventListener keyup
Formatting input field phone number with EventListener keyup

Time:09-16

I'm working on a form where I need the phone number field to reformat, as you type, into
xxx-xxx xx xx.
This in itself is straight forward and has been asked before but my problem is a bit different:

I've used the JavaScript only approach found in this fiddle, but to adjust to my wanted format I've edited the last code block into this:

const areacode = input.substring(0,3);
const gr1 = input.substring(3,6);
const gr2 = input.substring(6,8);
const gr3 = input.substring(8,10);

if(input.length > 7) {
      target.value = `${areacode}-${gr1} ${gr2} ${gr3}`;
    } else if(input.length > 5) {
      target.value = `${areacode}-${gr1} ${gr2}`;
    } else if(input.length > 2) {
      target.value = `${areacode}-${gr1}`;
    } else if(input.length > 0) {
      target.value = `${areacode}`;
    }

When I try this out in the fiddle, or paste in codepen for example, it works perfectly. But when I apply it to my site, it doesn't. The characters are replaced in a weird manner.


Suspicion: There's a constant containing a regex replace, like so:

const input = event.target.value.replace(/\D/g,'').substring(0,10);

I'm not good with RegEx but as this works in one place but not the other I feel I have to suspect this line of code.


CodePudding user response:

Experimenting with the code you provided in the question, I found that it works correctly indeed. Please don't post working code on StackOverflow asking what is wrong with it.

Nevertheless, I examined your website with a debugger and found an issue with the regex: Instead of using input.replace(/\D/g, ""), you wrote input.replace(/D/g, ""), which removes all D characters.

As a side note, I can highly recommend setting breakpoints in the browser source view to solve such problems.

  • Related