Tell us what’s happening:
- 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
<!-- file: index.html -->
<!DOCTYPE html>
<html>
<head>
<title>Telephone Number Validator</title>
<style>
.container {
max-width: 600px;
margin: 20px auto;
padding: 20px;
}
#user-input {
width: 300px;
padding: 5px;
}
#results-div {
margin-top: 10px;
}
.valid { color: green; }
.invalid { color: red; }
</style>
</head>
<body>
<div class="container">
<h1>Telephone Number Validator</h1>
<input id="user-input" type="text" placeholder="Enter phone number">
<button id="check-btn">Check</button>
<button id="clear-btn">Clear</button>
<div id="results-div"></div>
</div>
<script src="script.js">
</script>
</body>
</html>
/* file: script.js */
document.addEventListener('DOMContentLoaded', () => {
const userInput = document.getElementById('user-input');
const checkBtn = document.getElementById('check-btn');
const clearBtn = document.getElementById('clear-btn');
const resultsDiv = document.getElementById('results-div');
function validatePhoneNumber(input) {
input = input.replace(/[^0-9\s\(\)\-\+]/g, '');
const regex = /^(1\s?)?(\(\d{3}\)|\d{3})([\s\-]?)\d{3}([\s\-]?)\d{4}$/;
return regex.test(input);
}
checkBtn.addEventListener('click', () => {
const input = userInput.value.trim();
if (!input) {
alert('Please provide a phone number');
return;
}
const isValid = validatePhoneNumber(input);
const result = document.createElement('div');
result.textContent = `${isValid ? 'Valid US number: ' : 'Invalid US number: '} ${input}`;
result.className = isValid ? 'valid' : 'invalid';
resultsDiv.innerHTML = '';
resultsDiv.appendChild(result);
});
clearBtn.addEventListener('click', () => {
resultsDiv.innerHTML = '';
});
});
/* file: styles.css */
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