我试图检查jquery中的非负数。如果其他数字我的函数工作,但为零和非负数它不起作用。这里是我的示例小提琴。
Sample Fiddle
无法找到我的错误。谢谢。在jquery中验证数字
回答
约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;
});
if (isNaN($('#txtColumn').val() <= 0))
这是不对的..
您需要的值转换为整数,因为你检查,对整数
var intVal = parseInt($('#txtColumn').val(), 10); // Or use Number()
if(!isNaN(intVal) || intVal <= 0){
return false;
}
@Matt Lo:是的,确切的。谢谢:) – 2012-07-30 05:23:51
但是,如果用户在一个有效的整数之后输入无效的数据,那么这是行不通的。例如,'parseInt(“123.45abcdefg”,10)'返回'123'。还应该指定基数(第二个参数),或者'parseInt(“0x12”)'返回'18'和'parseInt(“010”)'返回'8' ... – nnnnnn 2012-07-30 05:33:58
@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
这应该工作:
$('#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()
忽略无效字符如果第一个字符是数字,但把他们的关心也
$('#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;
}
});
- 1. 只在jQuery验证中验证数字,括号和空格
- 2. jQuery验证数字粘贴
- 3. jquery验证只有数字
- 4. 验证文本框中的数字与jQuery验证
- 5. 在jquery中验证
- 6. jquery字母验证
- 7. jQuery的字母数字验证
- 8. 在JQuery中验证输入字段
- 9. jQuery验证只验证一个字段
- 10. 使用jQuery验证字段验证组
- 11. Backspace/Delete在Jquery字母数字验证中不起作用
- 12. Jquery允许在字母数字验证中使用空格
- 13. 如何在Javascript(Jquery)中定义验证器函数来验证输入字段?
- 14. Jquery验证不会正确验证数字吗?
- 15. Jquery验证数组
- 16. jQuery验证参数
- 17. 数字验证
- 18. jQuery验证 - 验证实际数据
- 19. jQuery验证:组验证,但不是字段验证
- 20. JQuery不验证大于9999的数字
- 21. jquery自定义验证非数字
- 22. jQuery的验证输入型数字
- 23. 在ASP.NET中的jQuery验证
- 24. 在jquery中合并验证
- 25. jquery动态字段验证
- 26. jquery字段验证onblur(mvc)
- 27. 验证动态字段jquery
- 28. jQuery验证瑞典字符
- 29. jquery验证依赖字段
- 30. jQuery验证2个字段
这有一点与* jQuery的做*。 – 2012-07-30 04:54:13