JavaScript Algorithms and Data Structures (Beta)

Hey I’m having an issue with my validation logic. My function is correctly identifying incorrect US numbers but incorrectly identifying the valid ones (reading them as invalid). I’ve tried adjusting whitespaces, making them optional and playing around with the hyphens. Am i missing an anchor or?

function validator() {
    const inputValue = input.value.trim();
    if (inputValue === "") {
        alert("Please provide a phone number");
    const countryCode = /^(1|\+1)?\s*?/;
const areaCode = /^(\(\d{3}\))?\s*?\d{3}/;
const mainNumber = /\s*?-\?\s*?\d{3}-?\s*?\d{4}/;
    const phoneRegex = new RegExp(`${countryCode.source}${areaCode.source}${mainNumber.source}`);

    if (phoneRegex.test(inputValue)) {
        results.textContent = `Valid US number: ${inputValue}`;
    } else {
        results.textContent = `Invalid US number: ${inputValue}`;

I’ve edited your code for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (').

I am not sure the regex /^(1|\+1)?\s*?^(\(\d{3}\))?\s*?\d{3}\s*?-\?\s*?\d{3}-?\s*?\d{4}/ will do what you want, considering the positions for start string I am not sure it can match anything

you can’t merge regexes like this and hipe they work

Ok thank you, ill try to condense it into one RegEx and see if that changes anything.