0

I'm trying to figure out why this doesn't work. I need to validate a telephone number in a form and my research show that this should work for a north American telephone number format.

I had /g at the end but that still didn't work...correctly formatted input is still false.

I used https://regex101.com/ and it looks like it is correct!

<!DOCTYPE html>
<html lang="en-US">

<head>
</head>

<body>  
    <section>
        <form>        
            <label for="phoneNumber">Phone Number
            </label>
            <input type="text" name="telephone" placeholder="Enter your Phone Number" />
        </form>
    </section>  
let telInput = form.querySelector("[name='telephone']"),
    tel = telInput.value;
//regex solution:
regex = /\([0-9]{3}\)\n[0-9]{3}-[0-9]{4}/;
if (!regex.test(tel)) {
        alert("You have to use (xxx) xxx-xxxx format.");
    telInput.focus();
        return;
    }
Dee
  • 5
  • 3
  • 2
    Possible duplicate of [A comprehensive regex for phone number validation](https://stackoverflow.com/questions/123559/a-comprehensive-regex-for-phone-number-validation) – imjared Aug 26 '19 at 14:37
  • 1
    replace the `\n` with a space and you also might use anchors `^` and `$` – The fourth bird Aug 26 '19 at 14:37
  • `\n` is a newline, `input` element does not allow entering newlines. Replace `\n` with `\s` or `\s*`, and yes, add anchors: `regex = /^\([0-9]{3}\)\s[0-9]{3}-[0-9]{4}$/;` or `regex = /^\([0-9]{3}\)\s*[0-9]{3}-[0-9]{4}$/;` – Wiktor Stribiżew Aug 26 '19 at 14:42
  • Thank you!!!! That did the trick! – Dee Aug 26 '19 at 14:43

1 Answers1

1

Your regex is very close! Try replacing \n (newline) with (space literal). Adding anchors ^$ also helps you avoid partial matches.

^\([0-9]{3}\) [0-9]{3}-[0-9]{4}$

Try it here!

Nick Reed
  • 4,989
  • 4
  • 17
  • 37