我想用最简单的故障安全测试来检查JavaScript中的字符串是否是正整数。
isNaN(str)为所有非整数值返回true, parseInt(str)为浮点字符串返回整数,如“2.5”。我也不想使用一些jQuery插件。
我想用最简单的故障安全测试来检查JavaScript中的字符串是否是正整数。
isNaN(str)为所有非整数值返回true, parseInt(str)为浮点字符串返回整数,如“2.5”。我也不想使用一些jQuery插件。
当前回答
根据上面VisioN的回答,如果你正在使用jQuery验证插件,你可以使用这个:
$(document).ready(function() {
$.validator.addMethod('integer', function(value, element, param) {
return (value >>> 0 === parseFloat(value) && value > 0);
}, 'Please enter a non zero integer value!');
}
然后你可以在你的常规规则集中使用或动态添加它,如下所示:
$("#positiveIntegerField").rules("add", {required:true, integer:true});
其他回答
ES6:
Number.isInteger(Number(theNumberString)) && Number(theNumberString) > 0
我的标准需要在@VisioN的答案上进行一些额外的检查。
不是负数,包括-0 不是小数部分为零的浮点数——0.0,1.000000 不是指数形式的数字,1e10
我发现这对于验证Express路由器的路由参数很有用。例如/书/:bookId
Code
/**
* Validate that a string is a positive integer
* Excludes float numbers with a zero decimal part, exponential notation and negative 0
* @param n
* @returns {boolean}
*/
function isStrictlyPositiveInteger(n) {
const nString = n.toString(), nInt = parseInt(n), nFloat = parseFloat(n);
// if a negative number (works on -0)
if (nString.charAt(0) === '-') {
return false;
}
// if an exponential like 1e10
if (nString.indexOf('e') > -1) {
return false;
}
// if a float number with a zero decimal part e.g 0.0
if ((nFloat === nInt) && (nString.indexOf('.') > -1)) {
return false;
}
// if a positive integer
// https://stackoverflow.com/a/10835227/8470877
return (0 === n % (!isNaN(nFloat) && 0 <= ~~n));
}
测试
"0" : true
"23" : true
"-10" : false
"10.30" : false
"-40.1" : false
"string" : false
"1234567890" : true
"129000098131766699.1" : false
"-1e10" : false
"1e10" : false
"1edf" : false
" " : false
"" : false
"0.01" : false
"0.00" : false
"-0" : false
"-0.0" : false
"0." : false
"-" : false
".1" : false
我的问题基本上是相同的:检查用户输入的数字是否为整数和正数。
我们的朋友Levi的代码和响应是我迄今为止在整个互联网上发现的最好的,在处理错误方面令人满意。
我在网站(https://bobbyhadz.com/blog/javascript-check-if-string-is-positive-integer):)上找到了下面的代码
function isPositiveInteger(str) {
if (typeof str !== 'string') {
return false;
}
const num = Number(str);
if (Number.isInteger(num) && num > 0) {
return true;
}
return false;
}
但是,对于1e10,它不能正确返回。
看起来正则表达式是可行的:
var isInt = /^\+?\d+$/.test('the string');
适用于node和90%以上浏览器(IE和Opera Mini除外)的现代解决方案是使用Number。isInteger后跟一个简单的正检查。
Number.isInteger(x) && x > 0
这是在ECMAScript 2015中完成的。
function isPositiveInteger(x) {
return Number.isInteger(x) && x > 0
}
Polyfil是:
Number.isInteger = Number.isInteger || function(value) {
return typeof value === 'number' &&
isFinite(value) &&
Math.floor(value) === value;
};
如果你需要支持字符串或数字形式的输入,那么你可以使用这个函数,在所有现有的答案(2/1/2018)在某种形式的输入上失败后,我写了一个大型测试套件。
function isPositiveInteger(v) {
var i;
return v && (i = parseInt(v)) && i > 0 && (i === v || ''+i === v);
}