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

Tell us what’s happening:

I cannot for the life of me figure out what I’m missing. I’ve gotten all except for:
5555555555 (valid)
555-555-5555 (valid)
(555)555-5555 (valid)
1 555)555-5555 (invalid)
-1 (757) 622-7382 (invalid)
11 555-555-5555 (invalid)

Your code so far

<!-- file: index.html -->
<html>
<head></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 result = document.getElementById("results-div");
const regex = /1{1,2}\s?[(]?[2-9][0-9][0-9][)]?-?\s?[2-9][0-9][0-9]-?\s?[0-9][0-9][0-9][0-9]/gi;

const check = () => {
  if (input.value === "") {
  alert("Please provide a phone number");
} else if (input.value.match(regex)) {
  result.innerText = "Valid US number: " + input.value;
} else {
  result.innerText = "Invalid US number: " + input.value;
}
}

const clear = () => {
  result.innerText = "";
}

checkBtn.addEventListener("click", check);
clearBtn.addEventListener("click", clear);
/* file: styles.css */

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.3 Safari/605.1.15

Challenge Information:

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

Hi there. Your regex expression aren’t handling the US numbers properly.

What do you mean? Am I supposed to use \d?
Other than that are there any problems?

Your regex has a few issues. The 1{1,2} pattern is incorrect because the US country code is only 1, not 11 or 111. Use 1? instead to make it optional. Missing anchors (^ and $) can cause partial matches, so they should be added. The g and i flags are unnecessary because phone numbers are case-insensitive, and g is only needed for multiple matches in a long text. Instead of [0-9][0-9][0-9], using \d{3} improves readability. The -?\s? repetition can be simplified using [-\s]?.

Thank you, I almost have it. Now I just need a way to make sure it knows that you can’t only have one parentheses at a time, it’s either both or none.

1 Like