簡體   English   中英

使用JavaScript / jQuery進行簡單的數字驗證

[英]Simple number validation using JavaScript / jQuery

在JavaScript / jQuery中是否有任何簡單的方法來檢查變量是否為數字(最好沒有插件)? 我想提醒變量是否為數字。

在此先感謝... :)

由於Java Script類型強制,我不建議使用isNaN函數來檢測數字。

例如:

isNaN(""); // returns false (is number), a empty string == 0
isNaN(true); // returns false (is number), boolean true == 1
isNaN(false); // returns false (is number), boolean false == zero
isNaN(new Date); // returns false (is number)
isNaN(null); // returns false (is number), null == 0 !!

您還應該記住, isNaN將為浮點數返回false(是數字)。

isNaN('1e1'); // is number
isNaN('1e-1'); // is number

我建議使用功能:

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

使用isNaN功能檢查號碼

var my_string="This is a string";
if(isNaN(my_string)){
document.write ("this is not a number ");
}else{document.write ("this is a number ");
}

要么

檢查一個號碼是否是非法號碼:

<script type="text/javascript">


    document.write(isNaN(5-2)+ "<br />");
    document.write(isNaN(0)+ "<br />");
    document.write(isNaN("Hello")+ "<br />");
    document.write(isNaN("2005/12/12")+ "<br />");

</script>

上面代碼的輸出將是:

false
false
true
true 

可以使用下面的代碼。 我不會完全依賴isNaN()。 isNaN向我顯示了不一致的結果(例如 - isNaN不會檢測到空格。)。

//Event of data being keyed in to textbox with class="numericField".
$(".numericField").keyup(function() {
    // Get the non Numeric char that was enetered
    var nonNumericChars = $(this).val().replace(/[0-9]/g, '');                                  
    if(nonNumericChars.length > 0)
        alert("Non Numeric Data entered");
});
function isDigit(num) {
    if (num.length>1){return false;}
    var string="1234567890";
    if (string.indexOf(num)!=-1){return true;}
    return false;
}

您需要遍歷字符串並為每個字符調用此函數

使用標准的javascript函數

isNaN('9')// this will return false
isNaN('a')// this will return true

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM