2012-07-30 59 views
2

我試圖檢查jquery中的非負數。如果其他數字我的函數工作,但爲零和非負數它不起作用。這裏是我的示例小提琴。
Sample Fiddle
無法找到我的錯誤。謝謝。在jquery中驗證數字

+1

這有一點與* jQuery的做*。 – 2012-07-30 04:54:13

回答

1

DEMO如何(注:錯誤消息是OP自己)

$('#txtNumber').keyup(function() { 
    var val = $(this).val(), error =""; 
    $('#lblIntegerError').remove(); 
    if (isNaN(val)) error = "Value must be integer value." 
    else if (parseInt(val,10) != val || val<= 0) error = "Value must be non negative number and greater than zero"; 
    else return true; 
    $('#txtNumber').after('<label class="Error" id="lblIntegerError"><br/>'+error+'</label>'); 
    return false; 
}); 
+0

非負_and_大於零?你的意思是_positive_? – nnnnnn 2012-07-30 05:19:06

+0

不是我的消息... – mplungjan 2012-07-30 05:21:23

0
if (isNaN($('#txtColumn').val() <= 0)) 

這是不對的..

您需要的值轉換爲整數,因爲你檢查,對整數

var intVal = parseInt($('#txtColumn').val(), 10); // Or use Number() 

if(!isNaN(intVal) || intVal <= 0){ 
    return false; 
} 
+0

@Matt Lo:是的,確切的。謝謝:) – 2012-07-30 05:23:51

+0

但是,如果用戶在一個有效的整數之後輸入無效的數據,那麼這是行不通的。例如,'parseInt(「123.45abcdefg」,10)'返回'123'。還應該指定基數(第二個參數),或者'parseInt(「0x12」)'返回'18'和'parseInt(「010」)'返回'8' ... – nnnnnn 2012-07-30 05:33:58

+0

@nnnnnn:那麼您需要指定基地。 'parseInt('010',10)'或者使用'Number('010')'。 'parseInt()'使用基數8作爲默認值。看到[這個SO問題](http://stackoverflow.com/questions/850341/workarounds-for-javascript-parseint-octal-bug)更多的。 – 2012-07-30 05:37:39

0

這應該工作:

$('#txtNumber').keyup(function() { 
    var num = $(this).val(); 
    num = new Number(num); 
    if(!(num > 0)) 
     $('#txtNumber').after('<label class="Error" id="lblIntegerError"><br/>Value must be non negative number and greater than zero.</label>'); 
}); 

注意:parseInt()忽略無效字符如果第一個字符是數字,但​​把他們的關心也

0
$('#txtNumber').keyup(function() 
{ 
    $('#lblIntegerError').remove(); 
    if (!isNaN(new Number($('#txtNumber').val()))) 
    { 
     if (parseInt($('#txtNumber').val()) <=0) 
     { 
       $('#txtNumber').after('<label class="Error" id="lblIntegerError"><br/>Value must be non negative number and greater than zero.</label>'); 
      return false; 
     } 


    } 
    else 
    { 
      $('#txtNumber').after('<label class="Error" id="lblIntegerError"><br/>Value must be integer value.</label>'); 
      return false; 
     } 
});​