我試圖檢查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