Javascript验证函数总是回复无效

时间:2015-02-06 22:23:15

标签: javascript validation

我已经完成了一切正确但仍然,对于所有值,该功能仅显示“无效”。谁能告诉我问题出在哪里?

<html>
<head>
<script>
function alpha()
{ 
var x = document.getElementById('input1'); 
var y = x.value;
var z = isNaN(y);
if(z<1 || z>10){console.log("Invalid");} else {console.log("valid");}
}
</script>
</head>

<body> 
<button id="but1" onmouseover="alpha()" style="background:blue;">Click Me</button> 
<p id=para1> Hello! This is paragraph One! </p> 
<input type=text id=input1 > 
</body> 
</html> 

提前致谢,抱歉问傻问题!但是,我无法找到代码出错的地方!

1 个答案:

答案 0 :(得分:2)

isNaN返回一个布尔值,并将其与数字进行比较。您需要将x与您的范围进行比较。

if(z || x<1 || x>10)

以下是我将如何清理你的代码

function alpha(){ 

    //name your variables something meaningful
    var userInputField = document.getElementById('input1');  

    //using parse int tells yourself and future programmers you want an int
    //it also gives you NaN if it's not a number so you don't have to check yourself
    //the 10 is the radix you want to convert to
    var userInputedValue = parseInt(x.value,10); 
    //check explicitly for NaN will save you some headaches
    if(userInputedValue === NaN || userInputedValue<1 || userInputedValue>10){
        console.log("Invalid");
    } else { 
         console.log("valid");
    }
}