I don’t know why this checker doesn’t recognize the input in my result-div
- When the #user-input element contains a valid US number and the #check-btn element is clicked, the #results-div element should contain the text "Valid US number: " followed by the number.
Failed:36. When the #user-input element contains an invalid US number and the #check-btn element is clicked, the #results-div element should contain the text "Invalid US number: " followed by the number.
Your code so far
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Telephone Number Validator</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="main-container">
<h1>Philippine Telephone Number Validator</h1>
<div class="container">
<h2>Enter a phone number</h2>
<input type="text" id="user-input">
<div class="result valid error" id="results-div"></div>
<div class="button-container">
<button id="check-btn">Check</button>
<button id="clear-btn">Clear</button>
</div>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
const inputUser = document.getElementById("user-input");
const checkBtn = document.getElementById("check-btn");
const clearBtn = document.getElementById("clear-btn");
const resultDisplay = document.getElementById("results-div");
const regex = /^1?\s*(\(\d{3}\)|\d{3})[\s*-]?\d{3}[\s*-]?\d{4}$/;
const checkInput = (input) => {
if (input === "") {
alert("Please provide a phone number");
return;
}
const phoneNum = document.createElement("p");
phoneNum.classList.add("result-number");
regex.test(input) ? (phoneNum.style.color = "green") : (phoneNum.style.color = "red");
const message = regex.test(input) ? `Valid US Number: ${input}` : `Invalid US Number: ${input}`;
const textNode = document.createTextNode(message);
phoneNum.appendChild(textNode);
resultDisplay.appendChild(phoneNum);
};
checkBtn.addEventListener("click", () => {
checkInput(inputUser.value);
inputUser.value = "";
});
clearBtn.addEventListener("click", () => resultDisplay.innerHTML = "");
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36
Challenge Information:
Build a Telephone Number Validator Project - Build a Telephone Number Validator