2013-04-01 125 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

不客氣。 :) –