Istiyak Istiyak - 6 months ago 11
Javascript Question

I want to Explore the whole character of a string like C Language in Javascript

I am trying a lot to do this but it does not return false flag when input was not number at all. whats the right way to explore each and every character in JAVAScript Like C Language .

var phonenumber = document.forms["signupform"]["phonenumber"].value;

var numberok = true;
var numberstr = "0123456789";

for(var i=0;i<phonenumber.length;i++){
for(var j=0;j<numberstr.length;j++){
if(phonenumber.charAt(i) != numberstr.charAt(j){
numberok = false;
break;
}
}
}

if(numberok == false ){

alert("Enter Correct Phone Number");
return false;
}

Answer

I set up your code to only use a single loop and use the indexOf method to see if the digit was in your numberstr.

In real code there are much better ways to see if something is a number, but I wanted to keep the methods you were using here, since you specifically asked about examining every number in the string.

var phonenumber = "9994";

var numberok = true;
var numberstr = "0123456789";

for (var i = 0; i < phonenumber.length; i++) {
  var char = phonenumber.charAt(i);
  // In modern browsers could also be written as:
  // var char = phonenumber[i];

  if (numberstr.indexOf(char) === -1) {
    numberok = false;
    break;
  }
}


if (numberok) {
    alert("Phone number is good");
} else {
  alert("Enter Correct Phone Number");
}