Need help with Validate US Telephone Numbers RegExp

I have a very specific problem. The RegExp I have correctly identifies US telephone numbers in all cases except one.
It will not identify this “(555)555-5555” and I can’t for the life of me figure out why.

This is my code :

function telephoneCheck(str) {
// Good luck!
var matched = str.match(/\b[1]?[-. ]?([(]\d{3}[)]|\d{3})[-. ]?\d{3}[-. ]?\d{4}\b/g);
if (matched === null) {
return false;
}
if (str === matched[0]) {
return true;
}
return false;
}

Any help is greatly appreciated.

You have basically two options to consider.

  1. We can fix the regex. This has a certain stink to it. Not that your regex is essentially bad, but there is a saying "Everyone knows that debugging is twice as hard as writing a program in the first place. So if you’re as clever as you can be when you write it, how will you ever debug it?"
    You need to put some additional checks in here:
    /\b[1]?[-. ]__________?([(]\d{3}[)]|\d{3})[-. ]?\d{3}[-. ]?\d{4}\b/g
    to look for the (ddd). I was able to put a working regex together, but reading these gives me a headache, and the more complex they are the harder they get to debug later on down the road when you revisit them months later.

  2. Alternately, you can break the code into a few different checks that are much simpler. Does the string have an absurd number of characters? Kick it. Does it have characters that don’t belong in a phone number? Kick it. Does it have unclosed parenthesis? Kick it. This challenge can be done with just a few very simple sanity checks.

It’s a choice that you have to make for yourself, and I can’t tell you which is the right way. But lines of code is not the only measure of quality, and sometimes it will save you a lot of sanity later to write simpler, more verbose code now, rather than condensed and clever code.

1 Like

Thanks for the reply, Vicky.

That is a very useful site, I finally got my regex working because of it.

I don’t think this will help anyone, but I don’t want to be like those people that say that they’ve figured something out and then don’t post the solution, so here it is:

/^[1]?[-. ]?(\(\d{3}\)|\d{3})[-. ]?\d{3}[-. ]?\d{4}$/gm

Thanks for the reply and for trying to read through that, Ken.

I definitely agree with your second point about breaking it down for readability’s sake.