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

Tell us what’s happening:

why does the commented out code allow the number 555-555–5555 (two hyphens)

but the new code says this is false and only allows one space or hyphen (which is what i want)

Your code so far

<!-- file: index.html -->

/* 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 resultsDiv = document.getElementById('results-div');

const checkValidNumber = input => {
    if (input === '') {
        alert('Please enter a number')
    }

    // const countryCode = '^(1\\s?)?';
    // const areaCode = '(\\([0-9]{3}\\))|([0-9]{3})[\\s\\-]?';
    // const phoneNumber = '[0-9]{3}[\\s\\-]?[0-9]{4}$';
    // const regex = new RegExp(
    //     `${countryCode}${areaCode}${phoneNumber}`
    // )

    const countryCode = '^(1\\s?)?';
    const areaCode = '(\\([0-9]{3}\\)|[0-9]{3})';
    const spacesDashes = '[\\s\\-]?';
    const phoneNumber = '[0-9]{3}[\\s\\-]?[0-9]{4}$';
    const phoneRegex = new RegExp(
      `${countryCode}${areaCode}${spacesDashes}${phoneNumber}`
    );

    console.log(phoneRegex.test(input));
}

checkBtn.addEventListener('click', () => {
    checkValidNumber(userInput.value);
})

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36

Challenge Information:

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

Welcome back to the forum @joewatson443

Here is a comparison of the new code and your old code.

The code in blue is the new code, the code in red is your old code.
The code in magenta is the overlap.

The old areaCode regex has a character class to match a dash after the area code.
The new regex will not match a dash. EDIT, apparently it does.

Happy coding

thanks for the image, I realised that in the old area code, I had the second 3 digit option in a capture group whereas in the new code, i didn’t, when I removed them in the old areaCode and tested it again it worked like the new one

// const areaCode = ‘(\([0-9]{3}\))|([0-9]{3})[\s\-]?’;

const areaCode = ‘(\([0-9]{3}\))|[0-9]{3}[\s\-]?’;

Hi @joewatson443

I just checked your new code, and it matches two hyphens, and also single hyphens.

The old regex also seems to match the same as the new regex.

ah sorry my fault, my original message was confusing.

I meant two consecutive hyphens like 555–555–5555.

Sorry my bad

I see only one hyphen, is that markdown smushing them togheter? use backticks around the number to show characters

yeh it’s smushing them together

so 555--555--5555

Testing them, none of the two allow the two dashes, can you show again a code snippet seeing this in action please?