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

Tell us what’s happening: any number is invalid am I missing something?

Describe your issue in detail here.

Your code so far

<!-- 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 chkbtn = document.getElementById("check-btn");
const clearbtn = document.getElementById("clear-btn");
const div = document.getElementById("results-div");


//const regx = /^(1\s?)?(\d{3}|\(\d{3}\))[\-\s]?\d{3}[\-\s]?\d{4}$/gm"


chkbtn.addEventListener('click',(e)=>{
  e.preventDefault()
  const regx = /^(1\s?)?(\d{3}|\(\d{3}\))[\-\s]?\d{3}[\-\s]?\d{4}$/gm;
  
  if(userinput.value === ""){
    alert("Please provide a phone number")
  }else if(userinput.value === regx){
    div.innerText = `Valid US number: ${userinput.value}`

  }else if(userinput.value !== regx){
    div.innerText = `Invalid US number: ${userinput.value}`
  }

   
  })


clearbtn.addEventListener('click',(e)=>{
    e.preventDefault()
     div.innerText = ""
     userinput.value= ""
})

Your browser information:

User Agent is: Mozilla/5.0 (iPhone; CPU iPhone OS 17_3_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.3.1 Mobile/15E148 Safari/604.1

Challenge Information:

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

You appear to have created this post without editing the template. Please edit your post to Tell us what’s happening in your own words.

Your regx is right and your code is perfet.

Except for one little thing,

You need to test the regx you created on the userinput.value,
If it passes, that’s a valid US number.
If not, it’s not a valid US number.

So instead of checking if the userinput.value equals regx:

You need to test your regx on the input.
For example:

const regx = /freeCodeCamp is awesome/i;
let str = "freeCodeCamp is awesome, for sure";

console.log(regx.test(str));         // output: true

and in your final case, instead of checking if the userinput.value doesn’t equal regx,
just make it the else statement. To work if all of above conditions are not true.

Appreciate it , it worked

1 Like

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