简体   繁体   中英

Validate number in jquery

I try to check non negative number in jquery.If other then number my function works but for zero and non negative number its doesn't work.Here is my sample fiddle.
Sample Fiddle
Unable to find my mistake.Thanks.

How about DEMO (NOTE: Error messages are OP's own)

$('#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;
});
if (isNaN($('#txtColumn').val() <= 0))

That's not right..

You need cast the value to an integer since you're checking against an integer

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

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

This should work:

$('#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>');
});

Note: The parseInt() ignores invalid characters if the first character is numeric but the Number() take cares of them also

$('#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;
        }
});​

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM