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

Tell us what’s happening:

Hey guys, just finished the project and I would like your feedback.

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">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>HTML 5 Boilerplate</title>
    <link rel="stylesheet" href="styles.css">
  </head>
  <body>

    <input id="user-input">
    <button id="check-btn">Check Number</button>
    <button id="clear-btn">Clear Number</button>
    <p id="results-div"></p>




	<script src="script.js"></script>
  </body>
</html>
/* file: styles.css */

/* file: script.js */
const userInput = document.getElementById('user-input');
const checkBtn = document.getElementById('check-btn');
const clearBtn = document.getElementById('clear-btn');
const results = document.getElementById('results-div');

const validFormats = [
"1 555-555-5555",
"1 (555) 555-5555",
"1(555)555-5555",
"1 555 555 5555",
"5555555555",
"555-555-5555",
"(555)555-5555",
]

const checkFormat = (input) => {
  for (let i = 0; i < validFormats.length; i++) {
    if (validFormats[i] === input) {
      return true
    } 
  }
  return false
}


checkBtn.addEventListener('click', () => {
  if (userInput.value === "") {
    alert("Please provide a phone number")
  }

  if (checkFormat(userInput.value)) {
    results.textContent = `Valid US number: ${userInput.value}`
  } else {
    results.textContent = `Invalid US number: ${userInput.value}`
  }
})

clearBtn.addEventListener('click', () => {
  results.textContent = ""
  userInput.value = ""
})

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36

Challenge Information:

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

Hi there, I moved your post to the code feedback category and added spoiler tags around it to blur it because it contains solution code.

Welcome to the forum @rolz33r01

It looks like you have hard-coded conditionals or variables that check for specific expected values. That is not solving this problem in the general case. Imagine if you were given different input values. Would your code be able to solve those problems?

To find out more about what hard-coding is or about why it is not suitable for solving coding questions, please read this post: Hard-coding For Beginners

Let us know if you have a question about how to make your code more flexible.

image

image

You are failing this test:

When the #user-input element contains 1 456 789 4444 and the #check-btn element is clicked, the #results-div element should contain the text “Valid US number: 1 456 789 4444”.

@Teller has pointed out why