Post your telephone validator solutions here!

Hey JavaScripters,

Congrats on doing the Telephone Validator project! :partying_face: :purple_heart:

Let’s post our solutions here! Here’s mine:

const RE = /^(1\s?)?\((\d{3})\)\s?\2-\d{4}$/;
const RE2 = /^(1\s?)?\d{3}(\s|-)?\d{3}(\s|-)?\d{4}$/;

// Create array of regexes
const REGEXES = [RE, RE2];

function telephoneCheck(str) {
  // loop through regexes
  for (let regex of REGEXES) {
    // if one matches, return true
    if (regex.test(str)) {
      return true;
    }
  }
  return false;
}
2 Likes

I’ve had fun trying to stay sane with this one. Looks terrifying, but passed the tests. What a relief :slightly_smiling_face:

function telephoneCheck(str) {
  let reg = /^(1\s?\-?)*(\(\d{3}\)|\d{3})[-\s]*\d{3}[-\s]*\d{4}$/;
  return reg.test(str);
}
11 Likes

WOW, nice one! A single regex! :scream:

1 Like

I admit it took almost 2 hours though, it’s finally time to rest :smile:

1 Like
let EX1=/^(1\s?)?\d\d\d-\d\d\d-\d\d\d\d$/;

let EX2=/^(1\s?)?\(\d\d\d\)\s?\d\d\d-\d\d\d\d$/;

let EX3=/^(1\s?)?\d\d\d\s?\d\d\d\s?\d\d\d\d$/;

let EX4=/^(1\s?)?\d\d\d\d\d\d\d\d\d\d$/;

function telephoneCheck(str) {

let result=false;

EX1.test(str)?result=true:EX2.test(str)?result=true:EX3.test(str)?result=true:EX4.test(str)?result=true:result=false;

  return  result;

}

console.log(telephoneCheck("1 555-555-5555"));

can you do it with zero regex :thinking: :thinking:

1 Like

I could not get the regex to work and not being confident in my regex skills I gave up and used code. I was thinking along the right lines but forgot about the ^ $

function telephoneCheck(str) {
  
  // fail early
  
  if (noAlpha(str)) {

    if (dataValidLen(str) !== 0) {

      if (dataValidLen(str) === 11) {
      
        // check formatting

        if (str[1] === " "){
          if (str[5] === " " && str[9] === " "){
            return true;
          }

          if (str[5] === "-" && str[9] === "-"){
            return true;
          }

          if (str[2] === "(" && str[6] === ")" && str[7] === " " && str[11] === "-") {
            return true;
          }

        }

        if (str[1] === "("){

          if (str[5] === ")" && str[9] === "-"){
            return true;
          }

        }
        
      }
      
      if (dataValidLen(str) === 10) {

        if (str.length === 10){
          // no formatting
          return true;
        }

        // check formatting

        if (str[3] === "-" && str[7] === "-"){
          return true;
        }

         if (str[3] === " " && str[7] === " "){
          return true;
        }

        if (str[0] === "("){

          if (str[4] === ")" && str[8] === "-"){
            return true;
          }

        }
        
      }

      console.log("Invalid format!");
      return false

    }

    console.log("Invalid number of digits!"); 
    return false;

  }

  console.log("Alpha chacters not allowed!");
  return false;

}

function noAlpha(str) {

  let alphaTest = /[A-z]/; // test for alpha 
  
  if (!alphaTest.test(str)){ // if no alpha continue
    return true;
  }

  return false;
}

function dataValidLen(str) {

  let formatTest = /(\W*)(\d)(\s*)/g; // group symbols and numeric
  let result = str.replace(formatTest, '$2' ); // extract numbers
  
  // data valid 11?
  if (result.length === 11 && result[0] === "1") {
    return 11;
  }

  // data valid 10?
  if (result.length === 10) {
    return 10;
  }

  // data invalid 
  return 0;
}

console.log(telephoneCheck("(223)456-7890"));

1 Like

That feels like a philosophical question! Sure, there must be lots of different ways to do the project, though I don’t think I will attempt it again for a long time.

1 Like

What about form validations where you want to check that the user’s input conforms to a standard before you submit the data to the server? I think I’m going to save this in my toolbox.

1 Like

Yes, also I got it done in one line!, hard but fun!

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

  return (check) ? true: false;
}
4 Likes

There’s one thing I don’t understand about the regex, if anyone can help:

For the first group of numbers, since they can have parenthesis or not, as in @gonzaloparada2671852 's solution you could write:

(\d{3}|\(\d{3}\))

However, why doesn’t it work if intead of parenthesis I use brackets? As in:

[\d{3}|\(\d{3}\)]

Does anybody know? :thinking:

1 Like

philosophy!!
just joking

Here is mine!

function telephoneCheck(str) {
  // Case that there is no parenthesis
  if((/^1?\s?\d{3}-?\s?\d{3}-?\s?\d{4}$/.test(str))) {
    return true;
  }
 // Case that there is parenthesis
  else if ((/^1?\s?\(\d{3}\)-?\s?\d{3}-?\s?\d{4}$/.test(str))) {
    return true;
  }
  else {
    return false;
  } 
}

The parentheses are for a group, the bracket will find any of the characters inside.
You can test this here (on w3schools.com): Tryit Editor v3.7
If you change the sample sentence to “Is this all red there is?”
The regex /[red]/g will match any of these letters and give you r,e,d,e,r,e
The regex /(red)/g will only match exactly that group and give you red as result.

4 Likes

Ahhhh, I get it now, thank you very much for the explanation!
I was confused because we had used [-|\s] in class, but I get now that, since it was just 1 char there, it was ok to use the brackets.
Thanks again! :smiling_face:

2 Likes

I played with this a bit as I was not happy with my original solution. Thought I will share it maybe somebody finds it useful :slight_smile:

//
// Revised attempt based on Ramón Huidobro's solution
//

// I could simply do this:
//  const regex = /^(1\s?)?\(\d{3}\)\s?\d{3}-\d{4}$|^(1\s?)?\d{3}(\s|-)?\d{3}(\s|-)?\d{4}$/;
//  return (regex.test(str))
// But then I can't give guidance to the user

function telephoneCheck(str) {

  const regex = /^(1\s?)?\(\d{3}\)\s?\d{3}-\d{4}$|^(1\s?)?\d{3}(\s|-)?\d{3}(\s|-)?\d{4}$/;

  // no alpha allowed
  if (!(/[A-z]/.test(str))){

    // get data
    const data = getData(str)

    // if len = 11 is country code = 1
    if (data.length === 11){

      if (data[0] !== "1"){
        //console.log("Invalid country code, must be 1");
        //return false;
        return("Invalid country code, must be 1");
      }

    }

    // data length
    if ((data.length === 11 && data[0] === "1") | data.length === 10){
      // check format

      if (regex.test(str)){
        //console.log("Ok!");
        //return true;
        return("Ok");
      }
      //console.log("Invalid format!");
      // return false
      return ("Invalid format!");

    }
    //console.log("Invalid number of digits!");
    //return false;
    return("Invalid number of digits!")

  }
  //console.log("Alpha chacters not allowed!");
  //return false;
  return ("Alpha chacters not allowed!");

}

function getData(str) {
  let formatTest = /(\W*)(\d)(\s*)/g; // group symbols, numeric and space
  let result = str.replace(formatTest, '$2' ); // extract numbers
  return result;
}

testNumbers = [
  // number, expected result
  ["1263457890", "Ok"],
  ["(263) 145-7890", "Ok"],
  ["263-145-7890", "Ok"],
  ["1(263)45-7890", "Invalid format!"],
  ["1(263)45-789", "Invalid number of digits!"],
  ["1(263)451-7890", "Ok"],
  ["2(263)451-7890", "Invalid country code, must be 1"]
]

let testResult = "";
let testStatus = [];
for (let i = 0; i < testNumbers.length; i++){

  //console.log(telephoneCheck(testNumbers[i][0]));
  testResult = (telephoneCheck(testNumbers[i][0]));

  if (testResult === testNumbers[i][1]){
    testStatus.push(`test ${i} ok`);
  }
  else {
    testStatus.push(`test ${i} fail`);
  }
}

console.log("Test Results: ", testStatus);
2 Likes
const TELEPHONEREGEX = /^1?(\s?((\(\d{3}\))|\d{3})(-?\s?)\d{3}(-?\s?)\d{4}$|\d{10}$)/;

function telephoneCheck(str) {
  return TELEPHONEREGEX.test(str);
}

My preferred solution has 3 regular expressions since it’s easier to read, but I did this one as an exercise of “Can you do this?”

I also used .test() rather than .match() since we only need to return whether the string fits a desired format and not what actually matched.

Yes, it can be done. And it is good technical solution. But what about the user? If you return false to the user the user will say ok, but what is incorrect? You could use it on the server side to check the input received via an API. The API does not want to get into a dialogue with the user.
On the frontend side you would want to give more useful feedback to the user. The API documentation would specify the expected format, so you want to ensure the user’s input conforms and when it does not you want to give specific guidance to the user. That is why I started playing with testing for specific conditions so that specific messages can be presented.
What’s interesting about this is that frontend validation could end up being more involved than backend validation. The use case impacts the code.

2 Likes

Oh, definitely. If the scope of this project were actual interaction with a user I’d approach it differently since just giving a false result isn’t particularly meaningful to them. I appreciate the effort you put into your expanded solution as it resembles what I’d like to see as an end user.

I wound up going to Felienne’s (this week’s guest) Twitter account and she touched on meaningful error messages and that’s been on my mind since.

1 Like

My soluction. I did it months ago

function telephoneCheck(str) {
  const pattern = /^1?[\s-]?((\(\d{3}\))|(\d{3}[\s-]?))[\s-]?\d{3}[\s-]?\d{4}$/
  const regExp = new RegExp(pattern)
  if(regExp.test(str))
    return true

  return false
}

const test = telephoneCheck("5555555555");

console.log(test);