验证jquery中的数字

时间:2012-07-30 04:52:11

标签: javascript validation

我尝试检查jquery中的非负数。如果是其他数字我的函数有效,但对于零和非负数,它不起作用。这是我的样本小提琴。
Sample Fiddle
无法找到我的错误。谢谢。

4 个答案:

答案 0 :(得分: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;
});

答案 1 :(得分:0)

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

那不对..

您需要将值转换为整数,因为您正在检查整数

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

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

答案 2 :(得分: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()如果第一个字符是数字但Number()同时处理它们,则会忽略无效字符

答案 3 :(得分: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;
        }
});​