JavaScript Algorithms and Data Structures Projects - Telephone Number Validator

Tell us what’s happening:
Describe your issue in detail here.
Why my does not work on these two cases
What i’m doing wrong here

telephoneCheck("27576227382")
should return
false

telephoneCheck("(275)76227382")
should return
false

.
Your code so far

function telephoneCheck(str) {
 let valid = /^\d{3}(\s|-)?\d{3}(\s|-)?\d{4}|^\(\d{3}\)(\s|-)?\d{3}(\s|-)?\d{4}|^1(\s|-)?\(\d{3}\)(\s|-)?\d{3}(\s|-)\d{4}|^1(\s|-)\d{3}(\s|-)\d{3}(\s|-)\d{4}/g

return valid.test(str)
  
}
console.log(telephoneCheck("555-555-5555"));

console.log(telephoneCheck("27576227382"))

console.log(telephoneCheck("(275)76227382"))



Your browser information:

User Agent is: Mozilla/5.0 (Linux; Android 11; Nokia 3.4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Mobile Safari/537.36

Challenge: JavaScript Algorithms and Data Structures Projects - Telephone Number Validator

Link to the challenge:

You should definitely look at the rules for a valid US phone number. Note also that this is a pretty good challenge as it’s one of those things that is an extremely common task IRL.

So these can’t work because the core scheme is 10 numbers optionally preceded with 1. So if there are 11 numbers, the first number has to be 1: it’s the country code. Both of the examples you’re showing have a 2 - that means you’re calling somewhere in Africa (or Greenland).

Personally, I don’t think regex is the correct tool here, but YMMV. But the pattern, which the challenge expects will defined as regex, should be something like:

  • An optional “1” or “+1” at the start
  • Then three digits. These may optionally be contained in brackets. So either “digit digit digit” or “(digit digit digit)” [1].
  • Then an optional space or hyphen or forward slash.
  • Then three digits.
  • Then an optional space or hyphen [2].
  • Then four digits.

  1. These digits are actually all defined, it isn’t just any digit. But for the purposes of the challenge, any three digits I think will pass.
  2. Afaik, if there isn’t a space or hyphen after the first three numbers, then there won’t be one here. But again, for purposes of challenge, simple version should pass.
1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.