Post your telephone validator solutions here!

Interesting. The use of the constructor is new to me. MDN states the following:

There are two ways to create a RegExp object: a literal notation and a constructor.

The literal notation’s parameters are enclosed between slashes and do not use quotation marks.
The constructor function’s parameters are not enclosed between slashes but do use quotation marks.

The following three expressions create the same regular expression object:

let re = /ab+c/i; // literal notation
let re = new RegExp('ab+c', 'i') // constructor with string pattern as first argument
let re = new RegExp(/ab+c/, 'i') // constructor with regular expression literal as first argument (Starting with ECMAScript 6)

The literal notation results in compilation of the regular expression when the expression is evaluated. Use literal notation when the regular expression will remain constant. For example, if you use literal notation to construct a regular expression used in a loop, the regular expression won’t be recompiled on each iteration.

The constructor of the regular expression object—for example, new RegExp('ab+c') —results in runtime compilation of the regular expression. Use the constructor function when you know the regular expression pattern will be changing, or you don’t know the pattern and obtain it from another source, such as user input.

2 Likes

That was one interesting talk for sure. I also want to look more into her content.

I totaly agree. For me regExp give us a hand full of ways to problem solve and it’s a tool that every programmer/developer most know.

Great minds! I did a similar one, but mine is slightly more convoluted. (Also you can see how many attempts I made at it by the variable name :slight_smile:

const pleaseWorkRegex = /^1?\s?(\(\d{3}\)|\s\d{3}\s|\d{3}|\d{3}-|\s\(\d{3}\)\s)\d{3}[-\s]?\d{4}$/

function telephoneCheck(str) {
    return pleaseWorkRegex.test(str)
}
2 Likes

Well done! I’ve done it in a quite similar way, but I just notice that mine will fail if the number starts with “1-”.

function telephoneCheck(phone){
  //console.log(`Phone: ${phone}`);
  const ref2= /(^1?)([\s]*)(\(\d{3}\)|\d{3})([\s-]*)(\d{3})([\s-]?)(\d{4}$)/
  return reg.test(phone)
2 Likes

I can definitely relate to this! I guess the next one in line would be iBegYouPleaseWorkThisTimeRegex :relieved:

2 Likes

Thank you! I guess putting the “-” inside the square brackets of the second group might solve that problem.

Someone also pointed out during the stream that this exercise does not validate actual US phone numbers, that the area code and the exchange part cannot start with 0 or 1. But that wasn’t the scope of this exercise, anyway, so that’s fine!

2 Likes

let reg = /^(\d{9})|(1\s)(\d{3})\s?|(\d{3})|\d{3}(\s|-)?\d{3}(\s|-)?\d{4}$/g

In this above regex, where I am making mistake. It is not checking for false numbers. Can anyone help me, please?

Hi Rivea,
Could you please explain to me the use of -? in (1\s?-?) and use of * between each group like
(1\s?-?)((\d{3})
\d{3})[-\s]
\d{3}[-\s]*\d{4}

Sure!
The reason I used “?” is that the space character or the hyphen is optional after “1”.
So, the number could be 1 555 555 5555, or 1-555-555-555, or 1 5555555555, etc.
Another way to put it, if there is “1”, there might be a space character or a hyphen following after it. That is optional.

* is a wildcard character that matches zero or more characters preceding it. For example, \d{3}[-\s]* would match a three-digit number that might be followed by a hyphen, or a space character after it. That is again, kind of like optional.

Now I realize that I could’ve actually used “?” after two of the [-\s] parts instead of *, since it could either be a hyphen or space character, but not both. As “?” matches zero or one characters preceding it, this would make better sense. So , something like 1 555- 555- 5555 wouldn’t be allowed.

Thank you for your question, hope that’s clear!

1 Like

Thanks, Rivea for the detailed answer !!

function telephoneCheck(str) {
  let regEx1 = /^[0-9]{3}-[0-9]{3}-[0-9]{4}$|^1\s[0-9]{3}-[0-9]{3}-[0-9]{4}/;
  let regEx2 = /^\d{10}$/;
  let regEx3 = /^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$|^1\s*\([0-9]{3}\)[0-9]{3}-[0-9]{4}$/;
  let regEx4 = /^\([0-9]{3}\)\s[0-9]{3}-[0-9]{4}$|^1\s*\([0-9]{3}\)\s[0-9]{3}-[0-9]{4}$/;
  let regEx5 = /^[0-9]{3}\s[0-9]{3}\s[0-9]{4}$|^1\s*[0-9]{3}\s[0-9]{3}\s[0-9]{4}$/;
  let regEx6 = /^1\s[0-9]{3}\s[0-9]{3}\s[0-9]{4}$/;
  
  if (regEx1.test(str) | regEx2.test(str) | regEx3.test(str)| regEx4.test(str) | regEx5.test(str) | regEx6.test(str)){
     return true;
  }
   
  return false;
  
}

console.log(telephoneCheck("555-555-5555"));//true
console.log(telephoneCheck("1 456 789 4444"));//true
console.log(telephoneCheck("27576227382"));//false
console.log(telephoneCheck("(6054756961)"));//false
console.log(telephoneCheck("1 555-555-5555"));//true
console.log(telephoneCheck("5555555555"));//true

I feel my superpowers are coming up gradually after completing this project. With a little revision and in-code testing, I was able to pull it off!

1 Like

I forgot all about regex and I felt lazy to review it. I only used it to remove the spaces between characters.

So I’ve come up with almost 150 lines of code as a solution :joy: This is kinda embarrassing :laughing: I’ll go build up another solution with regex hehe

Solution 1

function telephoneCheck(str) {
    // remove spaces
    let regexSpace = / /g;
    let newStr = str.replace(regexSpace, "")
  
    // sting to array
    let arr = newStr.split("")

    // object lookup
    const NUMBERS = [0,1,2,3,4,5,6,7,8,9]
    const DASH = ["-"]
    const PAR = ["(", ")"]
    
    // storage for characters in groups
    let checkArr4th = []
    let checkArr3rd = []
    let checkArr2nd = []

/*
to check patterns:
   1st = 1 or none 
   2nd = (555) or 555- or 555
   3rd = 555- or 555
   4th = 5555

to count number of places:
   1st = 0-1 / 2nd = 3-5 / 3rd = 3-4 / 4th = 4
*/
  
// 4th grp check
    if(arr.length < 15 && arr.length > 9){
      for(let i = 1; i < 5; i++){
        if(NUMBERS.hasOwnProperty(arr[arr.length-i])){
          checkArr4th.unshift(arr[arr.length-i])
          if(checkArr4th.length === 4){
// 3rd grp check
            if(NUMBERS.hasOwnProperty(arr[arr.length-5])){
              for(let i = 5; i < 8; i++){
                if(NUMBERS.hasOwnProperty(arr[arr.length-i])){
                  checkArr3rd.unshift(arr[arr.length-i])
                }
                if(checkArr3rd.length === 3){
// 2nd grp check      
                  if(NUMBERS.hasOwnProperty(arr[arr.length-8])){
                    for(let i = 8; i < 11; i++){
                      if(NUMBERS.hasOwnProperty(arr[arr.length-i])){
                        checkArr2nd.unshift(arr[arr.length-i])
                      }
                      if(checkArr2nd.length === 3){
                        if(arr[arr.length-11] === '1' || arr[arr.length-11] === undefined){
                          if(arr[arr.length-12] === '' || arr[arr.length-12] === undefined){
                            return true
                          }
                        }
                      }
                    }
                  }
  
                  if(DASH.includes(arr[arr.length-8])){
                    for(let i = 9; i < 12; i++){
                      if(NUMBERS.hasOwnProperty(arr[arr.length-i])){
                        checkArr2nd.unshift(arr[arr.length-i])
                      }
                      if(checkArr2nd.length === 3){
                        if(arr[arr.length-12] === '1' || arr[arr.length-12] === undefined){
                          if(arr[arr.length-13] === '' || arr[arr.length-13] === undefined){
                            return true
                          }
                        }
                      }
                    }
                  }
  
                  if(PAR.includes(arr[arr.length-8]) && PAR.includes(arr[arr.length-12])){
                    for(let i = 9; i < 12; i++){
                      if(NUMBERS.hasOwnProperty(arr[arr.length-i])){
                        checkArr2nd.unshift(arr[arr.length-i])
                      }
                      if(checkArr2nd.length === 3){
                        if(arr[arr.length-13] === '1' || arr[arr.length-13] === undefined){
                          if(arr[arr.length-14] === '' || arr[arr.length-14] === undefined){
                            return true
                          }
                        }
                      }
                    }
                  }
  
                }
              }
            }
// 3rd grp check                      
            if(DASH.includes(arr[arr.length-5])){
              for(let i = 6; i < 9; i++){
                if(NUMBERS.hasOwnProperty(arr[arr.length-i])){
                  checkArr3rd.unshift(arr[arr.length-i])
                }
                if(checkArr3rd.length === 3){
// 2nd grp check
                  if(NUMBERS.hasOwnProperty(arr[arr.length-9])){
                    for(let i = 9; i < 12; i++){
                      if(NUMBERS.hasOwnProperty(arr[arr.length-i])){
                        checkArr2nd.unshift(arr[arr.length-i])
                      }
                      if(checkArr2nd.length === 3){
                        if(arr[arr.length-12] === '1' || arr[arr.length-12] === undefined){
                          if(arr[arr.length-13] === '' || arr[arr.length-13] === undefined){
                            return true
                          }
                        }
                      }
                    }
                  }
  
                  if(DASH.includes(arr[arr.length-9])){
                    for(let i = 10; i < 13; i++){
                      if(NUMBERS.hasOwnProperty(arr[arr.length-i])){
                        checkArr2nd.unshift(arr[arr.length-i])
                      }
                      if(checkArr2nd.length === 3){
                        if(arr[arr.length-13] === '1' || arr[arr.length-13] === undefined){
                          if(arr[arr.length-14] === '' || arr[arr.length-14] === undefined){
                            return true
                          }
                        }
                      }
                    }
                  }
  
                  if(PAR.includes(arr[arr.length-9]) && PAR.includes(arr[arr.length-13])){
                    for(let i = 10; i < 13; i++){
                      if(NUMBERS.hasOwnProperty(arr[arr.length-i])){
                        checkArr2nd.unshift(arr[arr.length-i])
                      }
                      if(checkArr2nd.length === 3){
                        if(arr[arr.length-14] === '1' || arr[arr.length-14] === undefined){
                          if(arr[arr.length-15] === '' || arr[arr.length-15] === undefined){
                            return true
                          }
                        }
                      }
                    }
                  }
  
                }
              }
            }
  
          }
        }
      }
    }
    if(arr.length > 14){
      return false
    }
    return false
  
  }
  console.log(telephoneCheck("1 555-555-5555"))

After reviewing my notes, watching the vid a bit, and getting stuck with using the [ ] or ( ) to group patterns, I finally came up with a solution using regex :woozy_face: :joy:

(and they say give the task to a lazy person bc it will be done sooner through easier ways :laughing:)

Solution 2

function telephoneCheck(str) {
  let regex = /^(1\s?)?(\(\d{3}\)|\d{3}\-|\d{3})\s?(\d{3}\-|\d{3})\s?\d{4}$/;
  return regex.test(str);
}

I was stuck on [ ] for grouping the patterns and kept on wondering why it doesn’t work. So thank you very much for the explanation, Ilona :blush:

1 Like