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?
That does look correct, as pseudo-code; the actual JavaScript syntax for a regex-test is:
(Notice the
^and$; without them, it will match even ifphoneValmerely contains a phone number as a substring.)That said, I’m not sure that this part:
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.