我想用最简单的故障安全测试来检查JavaScript中的字符串是否是正整数。

isNaN(str)为所有非整数值返回true, parseInt(str)为浮点字符串返回整数,如“2.5”。我也不想使用一些jQuery插件。


当前回答

看起来正则表达式是可行的:

var isInt = /^\+?\d+$/.test('the string');

其他回答

大多数情况下,您需要这种类型的数据库使用检查,如检查字符串是否有效的userId。正因为如此,不可能有任何奇怪的符号可以被分割成整数。此外,整数应该在数据库的整数范围内。你只需要普通的整数,比如1 2 3等等。

const isStrNormPosInt = (str: string) => {
  return /^([1-9]\d*)$/.test(str) && Number(str) <= 2147483647 // postgres max int
}

如果检查通过了,你可以把它转换成number number (str)

我的标准需要在@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

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

在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;
}

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

看起来正则表达式是可行的:

var isInt = /^\+?\d+$/.test('the string');