Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript phone number validation

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?

like image 642
Federico klez Culloca Avatar asked Mar 05 '10 10:03

Federico klez Culloca


1 Answers

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.

like image 168
Erik Avatar answered Oct 23 '22 07:10

Erik