0

I have a function to validate phone number in a contact form, but i need to be able to put in "xxx xxx xxxx" for example, and not just "xxxxxxxx"

The number format should be:

xxx xxx xxxx

xxx-xxx-xxxx

xxx.xxx.xxxx

  function validatePhone() {
    var phone = document.getElementById("phone").value;

    if (phone.length == 0) {
      var w = document.getElementById("phoneError").textContent;
      alert(w);
      return false;
    }

    if (phone.length != 10) {
      var r = document.getElementById("phoneError").textContent;
      alert(r);
      return false;
    }

    // THIS IS NOT WORKING
    if (
      !phone.match(/^[0-9]{10}$/) ||
      !phone.match(/^\d{3}-\d{3}-\d{4}$/) ||
      !phone.match(/^\d{3}.\d{3}.\d{4}$/)
    ) {
      var t = document.getElementById("phoneError").textContent;
      alert(t);
      return false;
    }
  }
Hunter McMillen
  • 59,865
  • 24
  • 119
  • 170
  • consider an input mask...will be it easier on you and the user...there are a ton of them out there for jquery...easy to use – Ctznkane525 Apr 09 '18 at 18:26
  • Can you elaborate on the "This is not working" part, which cases are failing? – Hunter McMillen Apr 09 '18 at 18:26
  • A dash cannot be a dot. I imagine you intended to use `&&`. Also `RegExp.prototype.test` is probably more appropriate. – ASDFGerte Apr 09 '18 at 18:28
  • @HunterMcMillen I tested the others above, and they worked, so just added that comment yesterday for myself to remember, its part of a longer code (its a school assignment!) ^^, – jeanette__ Apr 09 '18 at 19:36

1 Answers1

0

Two things: First, you are mixing up AND and OR:

if (
  !phone.match(/^[0-9]{10}$/) ||
  !phone.match(/^\d{3}-\d{3}-\d{4}$/) ||
  !phone.match(/^\d{3}.\d{3}.\d{4}$/)
) {

As soon as one of the conditions fails, it will return false (which is basically always). You want this if to apply, when none of the expressions matches, e.g. when all of them are false. Therefor, you have to use && instead of ||. Not a AND not b AND not c.

Second: your 3rd regex is a bit off: . means "any character", so this regex would also match "123x123y1234". You need to escape the dot with a backslash: /^\d{3}\.\d{3}\.\d{4}$/

Also, you can improve this code significantly. You have 5 conditions, which could all be handled in one (if you want to allow the input of "123.123 234", otherwise you will have to do it using 3 regex). And for just checking if a regex matches a string, you maybe should use test(), because it is just slightly faster (it won't matter in your case, but just out of principle).

You can reduce your code to:

if (/^\d{3}[\s-.]\d{3}[\s-.]\d{4}$/.test(document.getElementById("phone").value) === false) {
    alert (document.getElementById("phoneError").textContent);
    return false;
}
masterfloda
  • 2,908
  • 1
  • 16
  • 27