Build a Telephone Number Validator

Hey so I finished writing my JS for the Telephone Validator project.

Something weird happens and I can’t work out what’s going on…

So for a few of the numbers the validation function returns true, but then I run it again and it returns false, then true and back and forth. Here’s the JS code, can I get a hint?

const 
  input = document.getElementById('user-input'), 
  checkButton = document.getElementById('check-btn'),
  clearButton = document.getElementById('clear-btn'),
  results = document.getElementById('results-div'),
  testRegex = /(^1?)((\(\d{3}\))|(\d{3}))(\d{7}$)/g;

clearButton.addEventListener('click', () => {
  results.textContent = '';
})

checkButton.addEventListener('click', () => {
  if (!input.value) {
    alert('Please provide a phone number.')
  } else {
    console.log("input value = ", input.value, typeof input.value);
    validate(input.value);
    input.value = '';
  }
})

const validate = (str) => {
  const cleanedStr = str.replace(/[ -]/g, '');
  console.log('cleanedStr = ', cleanedStr, typeof cleanedStr);
  if (testRegex.test(cleanedStr)) {
    console.log('is valid number = ', true);
    results.innerHTML += `<p>Valid US number: ${input.value}</p>`
  } else {
    console.log('is valid number = ', false);
    results.innerHTML = `<p>Invalid US number: ${input.value}</p>`
  }
}; 

Hi there. We can’t help you until you tell us what exact errors you have. Which ones are returning true and returning false. Additionally, it will be helpful if you use the “Ask for Help” button so it automatically links the challenge and provides all the code relevant to the challenge.

Also please format your code properly. Every defined constant variable should be labeled with const. Not saying your variables are variables could make things a bit unpredictable.

Additionally, could you share your HTML? It’s necessary to fully reproduce the working state of code.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.