Javascript检查电话号码 - IF声明

时间:2016-08-08 13:42:22

标签: javascript validation

我的if语句不能100%工作;我基本上希望它检查长度和它的数字,但如果它留空,那么errtelno1的绿色文本和样式 - 你能帮我理解为什么吗?我是新来的......这是一个11位数字

if (document.getElementById("telno").value.length != 11 ) {
    document.getElementById("errtelno").style.display = "inline";
    document.getElementById("errtelno").style.visibility = "visible";
    document.getElementById("telno").style.border ='4px solid red';
    document.getElementById("errtelno").style.color = "green";
    document.getElementById("errtelno").style.fontWeight = "light";
    document.getElementById("errtelno").style.fontSize = "12px";
    isValid = false;
}   else
{       document.getElementById("telno").style.border ='2px solid green';
        document.getElementById("errtelno").style.color = "green";

}

if (document.getElementById("telno").value != /^\d+$/ ) {
    document.getElementById("errtelno1").style.display = "inline";
    document.getElementById("errtelno1").style.visibility = "visible";
     document.getElementById("telno").style.border ='4px solid red';
     isValid = false;
}   else
{       document.getElementById("telno").style.border ='2px solid green';
}
return isValid; 
}

2 个答案:

答案 0 :(得分:0)

一个小样本来缩短问题。只有一个样本...

var telno = document.getElementById("telno");
var errtelno = document.getElementById("errtelno");
var expr = /^\d+$/;
var isValid = (telno.value.length == 11 && expr.test(telno.value));

if(!isValid) {
  errtelno.style.display = "inline";
  errtelno.style.visibility = "visible";
  telno.style.border ='4px solid red';
  errtelno.style.color = "green";
  errtelno.style.fontWeight = "light";
  errtelno.style.fontSize = "12px";
}
else {
  telno.style.border ='2px solid green';
  errtelno.style.color = "green";
}
return isValid;

答案 1 :(得分:0)

空字段可以留空,此错误在变量expr中更改,其中表达式仅用于数字格式,在大括号中将变量长度加到11

// function to be called

function checkTel(){

// setting the variables

  var telno = document.getElementById("telno"); 
  var errtelno = document.getElementById("errtelno");
  var expr = /^\d+${11}/;
  var isValid = (telno.value.length == 11 && expr.test(telno.value));

// changes box to highlighted red and error messages appear

if(!isValid) {
  document.getElementById("errtelno").style.display = "inline";
  document.getElementById("errtelno").style.visibility = "visible";
  document.getElementById("telno").style.border ='1px solid green';
  document.getElementById("errtelno").style.color = "green";
  document.getElementById("errtelno").style.fontWeight = "light";
  document.getElementById("errtelno").style.fontSize = "12px";
  } 

  // if it is blank or correct input then box turns green

  else {
  document.getElementById("telno").style.border ='2px solid green';
  document.getElementById("errtelno").style.color = "green";
  }
return isValid;
}