Build a Telephone Number Validator

Hello, World!

I completed my code and tried to key in phone numbers and all is read correctly - if valid/invalid, however, my code wont go thru and stuck at #7.

Please advise.

Thank you!

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" type="text/css" href="./styles.css" />
  <title>Telephone Number Validator</title>
</head>
<body>
  <input id="user-input" />
  <button id= "check-btn">CHECK
  </button>
  <button id= "clear-btn">CLEAR
  </button>
  <div id="results-div">
  </div>
  <script src="./script.js"></script>
</body>
</html>
const input = document.getElementById("user-input");
const checkBtn = document.getElementById("check-btn");
const clearBtn = document.getElementById("clear-btn");
const results = document.getElementById("results-div");

checkBtn.addEventListener("click", () => {

  let phoneNumber = input.value;    
  
  if (phoneNumber === "") {
    alert("Please provide a phone number");
    return;
  }

  const checkIfValid = (phoneNumber) => {

    let countryCode = /^(\+?1)?/;
    let spaceHyphen = /[\s-]?/;
    let areaCode = /(\d{3}|\(\d{3}\))/; 
    let mainNum = /(\d{3}\d{4}$|\d{3}[\s-]?\d{4}$)/;
    let pattern = countryCode.source + spaceHyphen.source + areaCode.source + spaceHyphen.source + mainNum.source;  
    let regexNum = new RegExp(pattern); 

    return regexNum.test(phoneNumber);
  }

  results.textContent = checkIfValid(phoneNumber) ? `"Valid US number: ${phoneNumber}"` : `"Invalid US number: ${phoneNumber}"`;

});

clearBtn.addEventListener("click", () => {
  input.value = "";
  results.innerText = "";
});

Can you also share a link to the project?

I’ve edited your code for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (').

I apologize for the err when sending my post.

Here’s the link to the project.

Welcome to the forum @Argee

Try removing the quote marks from the output text.

Happy coding

After I removed those quotes, completed user stories moved up to #35
then console logged an err “resultsDiv is not defined” so I changed my variable “results” to “resultsDiv” and then another one “userInput is not define” so I changed my variable “input” to “userInput”.

Completed script went thru!

Thanks all for your time and help!

1 Like