我想用最简单的故障安全测试来检查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});

其他回答

这几乎是一个重复的问题:

在JavaScript中验证十进制- IsNumeric()

答案是:

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

所以,一个正整数是:

function isPositiveInteger(n) {
  var floatN = parseFloat(n);
  return !isNaN(floatN) && isFinite(n) && floatN > 0
      && floatN % 1 == 0;
}
return ((parseInt(str, 10).toString() == str) && str.indexOf('-') === -1);

但是,如果您提供'0001'这样的字符串,则无法工作

根据上面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});

适用于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);
}

(~~a == a),其中a是字符串。