13

I need to validate a phone number in javascript. The requirements are:

they should be 10 digits, no comma, no dashes, just the numbers, and not the 1+ in front

this is what I wrote so far

function validatePhone(field,alerttxt) {
    with (field) {
        if(value.length > 10) {
            alert(alerttext);
            return false;
        }
        for(i = 0; i < value.length; i++) {
            if(parseInt(value[i]) == NaN) {
                alert(alerttxt);
                return false;
            }
        }
        return true;
    }
}
function validateForm(thisform) {
        if (validatePhone(phone,"Invalid phone number")==false) {
            phone.focus();
            return false;
        }

    }
}
  <form action="post.php" method="post" id="contactform" onsubmit="return validateForm(this)">
    <ol>
        <label for="phone">Your phone <span class="red"></span></label>
        <input id="phone" name="phone" class="text" />
      </li>
    </ol>
  </form>

but, obviously it doesn't work. How can I write the validatePhone() function so that it works?

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
  • 6
    What an unfriendly system. Let people enter spaces and dashes, then ignore them. And what about international phone numbers? – Quentin Mar 05 '10 at 10:43
  • This looks like a school assignment. For serious use, you *shouldn't* use regular expressions to [validate phone numbers properly](http://stackoverflow.com/a/4338544/1269037). – Dan Dascalescu Feb 26 '14 at 07:52
  • @DanDascalescu Actually, at that time, it wasn't a school assign. Just a shitty job on RentACoder – Federico klez Culloca Feb 26 '14 at 10:38

6 Answers6

30
phone = phone.replace(/[^0-9]/g, '');
if(phone.length != 10) { 
   alert("not 10 digits");
} else {
  alert("yep, its 10 digits");
} 

This will validate and/or correct based on your requirements, removing all non-digits.

Erik
  • 20,526
  • 8
  • 45
  • 76
  • 5
    as I said "validate and/or correct" is why not just match. Its pretty poor user experience to force someone to enter a phone number sans spaces or dashes when they are so easy to remove. – Erik Mar 05 '10 at 10:53
  • @FedericoCulloca: there is no "correct" regexp for the general case of validating phone numbers properly. [See why here.](http://stackoverflow.com/a/4338544/1269037) Aaron's answer is the only correct one on this page. – Dan Dascalescu Feb 26 '14 at 07:51
  • @DanDascalescu - No one asked for the general case. – Davor May 14 '14 at 07:19
11

Google's libphonenumber is very helpful for validation and formatting of phone numbers all over the world. It is easier, less cryptic, and more robust than using a RegEx, and it comes in JavaScript, Ruby, Python, C#, PHP, and Objective-C flavors.

Aaron Gray
  • 11,283
  • 7
  • 55
  • 61
  • 1
    *This*. People just don't seem to understand that [regular expressions are naive solutions](http://stackoverflow.com/questions/37684/how-to-replace-plain-urls-with-links/21925491#21925491) when it comes to validating real-world data. – Dan Dascalescu Feb 26 '14 at 07:44
7

You could use Regular Expressions:

function validatePhone(field, alerttext) {
    if (field.match(/^\d{10}/)) {
         return true;
    } 
    alert(alerttext);
    return false;
}
arnep
  • 5,971
  • 3
  • 35
  • 51
  • You *shouldn't*, in fact, use regular expressions to [validate phone numbers properly](http://stackoverflow.com/a/4338544/1269037). – Dan Dascalescu Feb 26 '14 at 07:50
  • His requirement says that he should check for a 10-digit-format without anything else. So this regular expression check should be ok. You are right: I dont like applications that force me into a specific phone number format. A check for minimum length, for numbers and some ()-+/ characters in any order might be ok, like in: `^[0-9 ()+/-]{5,}$` – arnep Feb 27 '14 at 07:59
1

Code to except only numbers braces and dashes

function DoValidatePhone() {
    var frm = document.forms['editMemberForm'];                
    var stripped = frm.contact.value;
    var isGoodMatch = stripped.match(/^[0-9\s(-)]*$/);
    if (!isGoodMatch) {
        alert("The Emergency Contact number contains invalid characters." + stripped);
        return false;
    }
}
Peter Brooks
  • 49
  • 10
0

Fixed function:

function validateForm(thisform) {
        if (validatePhone(thisform.phone,"Invalid phone number")==false) {
            thisform.phone.focus();
            return false;
        }
        return true;
}
antyrat
  • 27,479
  • 9
  • 75
  • 76
0

Add the pattern in which format you want directly in input tag.

<input id="phone" name="phone" pattern="\d{10}" class="text" />
Himabindu
  • 634
  • 8
  • 22