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

Tell us what’s happening:

I’m trying to complete the Telephone NumberValidator Test and I just can’t seem to get all the tests to pass even though my regex looks like it should validate/invalidate accordingly. "1 456 789 4444”, "1 (555) 555-5555”, “1(555)555-5555”, and “555-555-5555” will say valid and if I clear and paste again it will say invalid. Those are the only test not passing and I’m not sure how to fix the problem or if its even a problem with my regex

Your code so far

<!-- file: index.html -->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link
      href="style.css"
      rel="stylesheet"
    />
<title>Number Validator</title>
</head>

<body>
<input id="user-input"></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 checkBtn = document.getElementById("check-btn");
const clearBtn = document.getElementById("clear-btn")
const results = document.getElementById("results-div")

const validRegex = /^(1{1})?\s?(\([0-9]{3}\)|[0-9]{3})-?\s?[0-9]{3}-?\s?[0-9]{4}$/g;




const checkNumbers = () => {
  if (input.value === "") {
    alert("Please provide a phone number");
  }
  if (validRegex.test(input.value)) {
    results.innerHTML = `Valid US number: ${input.value}`
  }else {
    results.innerHTML = `Invalid US number: ${input.value}`
  }
  return
}

const clearNumbers = () => {
  input.value = ""
  results.innerHTML = "";

}


clearBtn.addEventListener("click", clearNumbers);
checkBtn.addEventListener("click", checkNumbers);
/* 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/126.0.0.0 Safari/537.36

Challenge Information:

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

If you want to check your regex, goto the website below and test it with the different telephone numbers.

(Make sure to set the regex flavor setting to ECMAScript)

I should say: your regex should not be defined in the global scope because the tests run consecutively and the way the regex test function works, it remembers the location of the last match and starts searching for a new match at the index it remembers (because you have the global switch on it). So that would make a mess of the tests.