Glenna
Glenna

Reputation: 145

JavaScript phone number validation using charCodeAt

I'd like to validate a phone number input using JavaScript to allow only number input. I prefer not to use regex, so I wrote a function like this:

function numberTest(){
 for(var i=0;i<phone_number.length;i++){
        if(phone_number.charCodeAt(i) >= 48 && phone_number.charCodeAt(i) <=57){
                    return true;
                    }else{
                    return false;
                    }
                }
            }

However it does not work. Any ideas why?

Upvotes: 0

Views: 388

Answers (2)

LcSalazar
LcSalazar

Reputation: 16821

The isNaN() (means is not a number) method will give you the reverted result in a simpler way...

var phone_number = "5511112223";
alert(isNaN(phone_number)); //returns false meaning it is a valid number
								
phone_number = "55aa1g11d12223";
alert(isNaN(phone_number)); //returns true meaning it is not a number

Upvotes: 0

ssube
ssube

Reputation: 48247

This doesn't work because it returns true after the first valid character. Neither branch will get past the first character, so you need to only return if you find an invalid character. Otherwise, if you reach the end without finding an invalid characters, you can finally return true.

Something like:

function numberTest(phone_number) {
  for (var i = 0; i < phone_number.length; i++) {
    if (phone_number.charCodeAt(i) < 48 && phone_number.charCodeAt(i) > 57) {
      return false;
    }
  }

  return true;
}

// Test various values
var testData = ["1234", "12ab", "123451234512345", "a1234123", "123123123a"];

var output = document.getElementById("results");
testData.forEach(function(test) {
  var next = document.createElement("li");
  next.textContent = numberTest(test);
});
<ul id="results"></ul>

Upvotes: 2

Related Questions