2012-10-06 54 views
2

可能重複:
Validate numbers in JavaScript - IsNumeric()的Javascript:驗證字段:沒空和僅包含數字

嗨,我嘗試使用JavaScript來確保字段不驗證字段空和只包含數字

我正在使用document.getElementById獲取該字段的值,然後使用此函數來驗證它:

function isNumeric(elem, message, messsage2) 
{ 
    if(isNaN(elem)) 
    { 
    alert(message2); 
    return false; 
    } 
    else if (elem == null || elem =="") 
    { 
    alert(message); 
    return false; 
    } 
return true; 
} 

但是這個功能還是讓我輸入字母那裏應該是數字

+1

你以爲你是試圖驗證數量與第一人在2012年的JavaScript? :)看到[這](http://stackoverflow.com/q/1779013/944681)或[這](http://stackoverflow.com/q/18082/944681) –

+0

這兩個職位正在驗證數字,我需要驗證不是空的和唯一的數字的函數。 – Neil

回答

1
function isNonEmptyNumber (str) { 
    if(!str.length) return false; 
    var num = +str; 
    return isFinite(num) && !isNaN(num); 
}