octorell
octorell

Reputation: 21

What's wrong with this validation function?

I can’t validate phone number with this regular expression /^(?(\d{3}))?[..-/]?(\d{3})[.-/ ]?(\d{4})$/; The first three digits goes in the parenthesis (xxx) xxx-xxxx. I try to test the phone number with if/else loop but something is not working and I can't find what I'm doing wrong. Thanks for your help.

function validatePhone() {
    var pNumber = document.getElementById("phoneprompt").value;
    var regex = /^\(?(\d{3})\)?[\.\.-\/]?(\d{3})[\.\-\/ ]?(\d{4})$/;

    if (regex.test(pNumber)) {
        document.getElementById("phoneprompt").innerHTML = "<img src=\"greencheck.png\" />";
        return (true);
    } else {
        document.getElementById("phoneprompt").innerHTML = "<img src=\"redcheck.png\" />&nbsp;Phone numbers must be in (xxx) xxx-xxxx format"; 
        return (false);
    }
}

Upvotes: 2

Views: 48

Answers (2)

Drakes
Drakes

Reputation: 23660

You can change

/^\(?(\d{3})\)?[\.\.-\/]?(\d{3})[\.\-\/ ]?(\d{4})$/

to

/^\(?(\d{3})\)?\s?[\.\.-\/]?(\d{3})[\.\-\/ ]?(\d{4})$/

to accommodate a space optionally being after the area code, so both (xxx) xxx-xxxx and (xxx)xxx-xxxx will be matched.


However, here is a more robust 10-digit phone number regex where brackets and dashes are optional:

/^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$/

These will all be matched:

(123)456-7890
(123) 456-7890
123-456-7890
123 456 7890

Ref: Regular expression to match standard 10 digit phone number

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

Other than the problem with the regex, you can't set innerHTML of an input filed, so

function validatePhone() {
  var el = document.getElementById("phoneprompt"),
    pNumber = el.value,
    regex = /^\(?(\d{3})\)?\s?[\.\.-\/]?(\d{3})[\.\-\/ ]?(\d{4})$/,
    valid = regex.test(pNumber);

  if (valid) {
    document.getElementById("phonepromptmsg").innerHTML = "<img src=\"greencheck.png\" />";
  } else {
    document.getElementById("phonepromptmsg").innerHTML = "<img src=\"redcheck.png\" />&nbsp;Phone numbers must be in (xxx) xxx-xxxx format";
  }

  return valid;
}
<input id="phoneprompt" onchange="validatePhone()" />
<span id="phonepromptmsg"></span>
<br />
<input type="button" onclick="validatePhone()" value="Test"/>

Upvotes: 1

Related Questions