Javascript 在javascript中检查文本字段的值是否为整数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4544165/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 12:52:56  来源:igfitidea点击:

checking if value of a textfield is integer in javascript

javascriptvalidation

提问by akshay

How can i check is a text entered in a textbox is an integer or not? I used the NAN function but it accepts decimal values too.

如何检查文本框中输入的文本是否为整数?我使用了 NAN 函数,但它也接受十进制值。

How can I do this? Is there any built-in method?

我怎样才能做到这一点?有没有内置方法?

回答by Brian Donovan

Let's say the text field is referenced by the variable intfield, then you can check it like this:

假设文本字段被变量引用intfield,那么您可以像这样检查它:

var value = Number(intfield.value);
if (Math.floor(value) == value) {
  // value is an integer, do something based on that
} else {
  // value is not an integer, show some validation error
}

回答by akshay

// validate if the input is numeric and between min and max digits
function validateNumberSize(inputtxt, min, max)
{
    var numbers = /^[0-9]+$/;
    if(inputtxt.match(numbers))
    {
        if(inputtxt.length >= min && inputtxt.length <= max)
        {
            return true;
        }
    }
    return false;
}

回答by mplungjan

Regular expressions would be a way:

正则表达式将是一种方式:

var re = /^-?\d\d*$/
alert(re.test(strNumber)); // leading or trailing spaces are also invalid here

Complete example with updates:

带有更新的完整示例:

http://rgagnon.com/jsdetails/js-0063.html

http://rgagnon.com/jsdetails/js-0063.html

function validateInteger( strValue ) {
/************************************************
DESCRIPTION: Validates that a string contains only
    valid integer number.

PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.
**************************************************/
  var objRegExp  = /(^-?\d\d*$)/;  

  //check for integer characters
  return objRegExp.test(strValue);
}


Updated to handle whitespace - which possibly is not allowed in the validation but here it is anyway: Possible to continue to use the code from the link I gave (leftTrim/rightTrim) but here I reuse trim from .trim() in JavaScript not working in IE

更新以处理空格 - 这可能在验证中是不允许的,但无论如何:可以继续使用我提供的链接中的代码 (leftTrim/rightTrim) 但在这里我重用来自.trim() 的修剪在 JavaScript 中不起作用在浏览器中

function ignoreLeadingAndtrailingWhitespace( strValue ) {
  return strValue.length>0?validateInteger( strValue.trim() ):false;
}

if(typeof String.prototype.trim !== 'function') { 
  String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, ''); 
  }
}


function validateInteger( strValue ) {
/************************************************
DESCRIPTION: Validates that a string contains only
    valid integer number.

PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.
**************************************************/
  var objRegExp  = /(^-?\d\d*$)/;

  //check for integer characters
  return objRegExp.test(strValue);
}

回答by álvaro González

Form data is always text. My suggestion is that you parse it as integer and compare it with the original:

表单数据始终是文本。我的建议是您将其解析为整数并将其与原始值进行比较:

var sampleData = ["not a number", "0", "10", "3.14", "-12", "-0.34", "2e10", "34foo", "foo34"];
var integers = [], notIntegers = [];
for(var i=0, len=sampleData.length; i<len; i++){
    var original = sampleData[i];
    var parsed = parseInt(original, 10);
    if( !isNaN(parsed) && original==parsed ){
        integers.push(parsed);
    }else{
        notIntegers.push(original);
    }
}
alert("Integers: " + integers.join(", ") + "\nNot integers: " + notIntegers.join(", "));

This shows:

由此可见:

Integers: 0, 10, -12
Not integers: not a number, 3.14, -0.34, 2e10, 34foo, foo34

Scientific notation is not supported, neither thousand separators. If it's an issue, you need something different ;)

不支持科学记数法,也不支持千位​​分隔符。如果这是一个问题,你需要一些不同的东西;)

Update:I want to make clear that this is only one of the possible approaches, not the one and only Truth. This approach makes sense if you need to do math with the data so you have to get a numeric variable anyway.

更新:我想明确指出,这只是一种可能的方法,而不是唯一的真理。如果您需要对数据进行数学运算,则这种方法很有意义,因此无论如何您都必须获得数字变量。

回答by Raghav

If you are looking either for integer or decimal you can go for:

如果您正在寻找整数或小数,您可以去:

function IsNumeric(input)
{
   return (input - 0) == input && input.length > 0;
}

回答by karim79

var num = document.getElementById("myField").value;
if(/^\d+$/.test(num)) {
    // is an int
}

回答by selfboot

Best to use the regular expression as follows:

最好使用正则表达式如下:

function isInteger(str) {
    var r = /^-?[0-9]*[1-9][0-9]*$/;
    return r.test(str);
}

Just a test demo:

只是一个测试演示:

> function isInteger(str) {
...     var r = /^-?[0-9]*[1-9][0-9]*$/;
...     return r.test(str);
... }
> isInteger("-123")
true
> isInteger("a123")
false
> isInteger("123.4")
false