2013-04-01 126 views
0

到目前为止,但不会工作?年龄验证Javascript

//if no age was entered it will allow 
var age=document.getElementById('age1').value; 
if(age == "")  
    return true; 

//check if age is a number or less than or greater than 100 
if (isNaN(age)||age<1||age>100) 
{ 
    alert("The age must be a number between 1 and 100"); 
    return false; 
} 

我只是需要验证!!!!

回答

0

你会想parseInt()返回到年龄值,因为它作为一个字符串。

0

您应该使用parseInt(value, radix)将字符串转换为数字。使用这种方法时,提供radix是一种很好的做法。在你的情况下,它是一个小数,所以radix10

试试这个:

//if no age was entered it will allow 
var age=document.getElementById('age1').value; 
if(age === "") { 
    return true; 
} 

// convert age to a number 
age = parseInt(age, 10); 

//check if age is a number or less than or greater than 100 
if (isNaN(age) || age < 1 || age > 100) 
{ 
    alert("The age must be a number between 1 and 100"); 
    return false; 
} 
1

尽量快捷+转换成Number,或使用parseInt(value, 10)

var age = +document.getElementById('age1').value; 

if (!(age > 1 && age<100)){ 

     alert("The age must be a number between 1 and 100"); 
     return false; 
} 

return true; 
0

你为什么不使用正则表达式来验证这一点。使用下面的正则表达式是:

/^[1-9]?[0-9]{1}$|^100$/ 

此正则表达式相匹配的数1个或2位数字,或100:

+0

很好的建议,但你想给一个更具体的正则表达式模式。尝试对'donotmatch100','donotmatch10or0'和'donotmatch10or0orme'的正则表达式。 –

+0

Thiks @Tanzeel Kazi,我已更新回答 –

+0

不客气。 :) –