2012-07-30 60 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; 
     } 
});​