Build a Telephone Number Validator Project - Build a Telephone Number Validator

Tell us what’s happening:

Always says false for anything that I put in. Can’t find out why.
const regex = /^(1\s?)?((\d{3})|d{3})([\s-]?)\d{3}([\s-]?)\d{4}$/

Your code so far

<!-- file: index.html -->
<!DOCTYPE html>
<html lang="en">
  <head>
    <title></title>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <link rel="stylesheet" href="styles.css"/>
  </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>

/* file: script.js */
const input = document.getElementById("user-input");
const check = document.getElementById("check-btn");
const clear = document.getElementById("clear-btn");
const result = document.getElementById("results-div");

check.addEventListener("click", () => {
const regex = /^(1\s?)?(\(\d{3}\)|d{3})([\s-]?)\d{3}([\s-]?)\d{4}$/

  if (!input.value) {
    alert("Please provide a phone number");
  } else if (regex.test(input.value)) {
    result.innerText = `Valid US number: ${input.value}`
  } else {
    result.innerText = `Invalid US number: ${input.value}`
  }
});

clear.addEventListener("click", () => result.innerText = "");
/*
Regex:

  Optional 1 with a space: (1\s?)?
  3 digits with optional (): (\(\d{3}\)|d{3})
  Optional - or space: ([\s-]?)
  Three digits: \d{3}
  Optional - or space: ([\s-]?)
  4 digits: \d{4}
*/
/* file: styles.css */

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36

Challenge Information:

Build a Telephone Number Validator Project - Build a Telephone Number Validator

Hi there!

There is a small issue in the regex pattern. d{3} should be \d{3} in the second capturing group. Without the backslash (\), it doesn’t represent a digit pattern.

Sorry, still didn’t work.
const regex = /^(1\s?)?((\d{3})|\d{3})([\s-]?)\d{3}([\s-]?)\d{4$/

You have removed a slash before that capture group.

And have removed the } bracket after 4.

1 Like