Dee
Dee

Reputation: 15

I'm trying to use regex to validate a telephone number in javascript

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;
    }

Upvotes: 0

Views: 71

Answers (1)

Nick Reed
Nick Reed

Reputation: 5059

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!

Upvotes: 1

Related Questions