Build a Telephone Number Validator Project - Build Step 12a Telephone Number Validator

Tell us what’s happening:

Describe your issue in detail here.
Issue with Step 12: Is there something wrong with my regex variable the reason it keeps showing the phone number as valid?


Your code so far

<!-- file: index.html -->
<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="/styles.css">
    <label for="user-input">Enter a Phone Number:</label>
    <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>
/* file: styles.css */

/* file: script.js */
const userInput = document.getElementById('user-input')
const checkBtn = document.getElementById('check-btn')
const clearBtn = document.getElementById('clear-btn')
const resultDiv = document.getElementById('results-div')

const regex = /^1?\s?\(?\d{3}\)?\s?-?\d{3}-?\d{4}$/

checkBtn.addEventListener('click', () => {
    const phoneNumber = userInput.value.trim();
    console.log("Input phone number:", phoneNumber); 
    if (!phoneNumber) {
        alert("Please provide a phone number");
    if (regex.test(phoneNumber)) {
        resultDiv.textContent = `Valid US number: ${phoneNumber}`;
    } else {
        resultDiv.textContent = `Invalid US number: ${phoneNumber}`;

clearBtn.addEventListener('click', () => {
    resultDiv.textContent = ""

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/ Safari/537.36

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.

Hi there. According to your code, the following sample number isn’t valid.

1 555 555 5555

And if it is showing some numbers as valid , it is indeed safe to assume there is an issue with your regex somewhere. I’ll give you a hint. It fails before the last four numbers.

Always test your regex. Happy coding. :slight_smile:

P. S I recommend using regex101: build, test, and debug regex or installing a local Visual Studio Code extension for this challenge.

1 Like