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

… ### Tell us what's happening: const userInput = document.getElementById('user-input'); const checkBtn = document.getElementById('check-btn'); const clearBtn = document.getElementById('clear-btn'); const results = document.… results.textContent = "" };

checkBtn.addEventListener(‘click’, checkInput);
clearBtn.addEventListener(‘click’, clearResults);

Your code so far

<!-- file: index.html -->
<!-- file: index.html -->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <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: 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 tenDigits = /^(:?\d{10})$/;
const hyphSpace = /^(:?\d{3}[-\s]?\d{3}[-\s]?\d{4})$/;
const parenths = /^(:?\(\d{3}\)\s?\d{3}[-\s]?\d{4})$/;
const begOne = /^1\s?\(?\d{3}\)?[-\s]?\d{3}[-\s]?\d{4}$/;
const phonelist = [tenDigits, hyphSpace, parenths, begOne]

const isValid = (numb) => phonelist.some(regex => regex.test(numb));

const checkInput = () => {
  if(userInput.value === ''){
    alert("Please provide a phone number");
    return;
  }
  results.textContent = isValid(userInput.value)
    ? `Valid US number: ${userInput.value}`
    : `Invalid US number: ${userInput.value}`;
  userInput.value = "";
};

const clearResults = () => {
  results.textContent = ""
};

checkBtn.addEventListener('click', checkInput);
clearBtn.addEventListener('click', clearResults);

Your browser information:

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

Challenge Information:

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

#user-input 元素包含 1 555)555-5555 并单击 #check-btn 元素时,#results-div 元素应包含文本“无效的美国编号:1 555)555-5555” 。 报这个错麻烦大神们帮忙

Please Tell us what’s happening in your own words.

Learning to describe problems is hard, but it is an important part of learning how to code.

Also, the more you say, the more we can help!

You have not returned yet to explain your problem, but I will make one observation: looking at your regular expressions I don’t think you have taken account of the situation where there is just one (left or right) parentheses round the first set of digits missing - if there is only one parentheses it should fail of course.

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