Steven Matthews
Steven Matthews

Reputation: 11285

Regular Expressions and Javascript and Phone Numbers

I am trying to figure out how to use a regular expression to validate a phone number in Javascript.

So far my thoughts are to get the value when the form is submitted, and compare them to a regular expression. How would I go about doing that in Javascript? My pseudo-code so far looks sorta like this:

phoneVal = document.getElementById("phone");

if (phoneVal == \d{3}-\d{3}-\d{4}) {
    return True;
}
else if (phoneVal == \d{10}) {
    <string methods to add hyphens to an unbroken number>
    return True;
}

etc, etc

Does this look correct?

EDIT: How would I deal with parenthesis while in an if statement?

For example, /(\d{3}) \d{3}-\d{4}/, only it'd be inside of if( ) so there might be a parsing problem?

Upvotes: 1

Views: 365

Answers (2)

ruakh
ruakh

Reputation: 183301

That does look correct, as pseudo-code; the actual JavaScript syntax for a regex-test is:

if(/^\d{3}-\d{3}-\d{4}$/.test(phoneVal))

(Notice the ^ and $; without them, it will match even if phoneVal merely contains a phone number as a substring.)

That said, I'm not sure that this part:

<string methods to add hyphens to an unbroken number>

is useful. You'll want to re-perform all of your validations and normalizations on the server-side, anyway, where you can guarantee that they actually take place; the only benefit of client-side JavaScript validation is to present error-messages in a more user-friendly way when possible. Without seeing the rest of your application, I can't say for sure, but I would guess that there's no real benefit in adding hyphens in this client-side code.

Upvotes: 1

Joe
Joe

Reputation: 82604

phoneVal = document.getElementById("phone");

if (/\d{3}-\d{3}-\d{4}/.test(phoneVal)) {
    return True;
}
else if (/\d{10}/.test(phoneVal )) {
    // <string methods to add hyphens to an unbroken number>
    return True;
}

or

return /\d{10}|\d{3}-\d{3}-\d{4}/.test(phoneVal )

Upvotes: 0

Related Questions