Tell us what’s happening:
Hey, I’m having trouble with getting my Regex to work, the ternary operator always comes back false.
I’m guessing it’s something to do with the Regex but I’ve checked it over a bunch with no avail to get it working.
Thanks for your time
Your code so far
<!-- file: index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"></meta>
<meta name="viewport" content="width=device-width, initial-scale=1.0"></meta>
<title>Telephone Number Validator</title>
<link rel="stylesheet" href="styles.css"></link>
</head>
<body>
<label>Please enter a Phone Number:</label>
<input id="user-input" type="text">
<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 userInput = document.getElementById("user-input");
const checkBtn = document.getElementById("check-btn");
const clearBtn = document.getElementById("clear-btn");
const results = document.getElementById("results-div");
const checkPhoneNumber = input => {
if (input === "") {
alert("Please provide a phone number");
return
}
const countryCode = /^(1\s?)?/;
const areaCode = /(?:\(?([0-9]{3})\)?)/;
const space = /[-\s]?/;
const phoneNumber = /([0-9]{3})[-\s]?([0-9]{4})$/;
const phoneRegex = new RegExp(`${countryCode}${areaCode}${space}${phoneNumber}`);
const resultText = document.createElement("p");
resultText.className = "result-text";
resultText.textContent = `${phoneRegex.test(input) ? "Valid" : "Invalid"} US number: ${input}`
results.appendChild(resultText);
}
checkBtn.addEventListener("click", () => {
checkPhoneNumber(userInput.value);
userInput.value = "";
});
userInput.addEventListener("keydown", e => {
if (e.key === "Enter") {
checkPhoneNumber(userInput.value);
userInput.value = "";
}
})
clearBtn.addEventListener("click", () => {
results.innerText = "";
});
/* file: styles.css */
#results-div {
color: black;
size: 20px;
}
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 Edg/130.0.0.0
Challenge Information:
Build a Telephone Number Validator Project - Build a Telephone Number Validator