简体   繁体   English

验证文本输入是否为数字-JavaScript

[英]Validating text input as a number - JavaScript

I am trying to validate user input to make sure that what they type (if anything - field is not required) is a number. 我正在尝试验证用户输入,以确保他们输入的内容(如果有的话-不需要字段)是一个数字。 Now I don't care what this number is, but it must be an integer. 现在我不在乎这个数字是多少,但它必须是整数。 Negative, positive, whatever is validated later on. 消极的,积极的,无论以后如何验证。 Here is my test sample so far: 到目前为止,这是我的测试样本:

var a=["",0,"0",-2,"-2",2,"2",-2.2,"-2.2",2.2,"2.2",-1,"-1",undefined,null,NaN,Infinity,-Infinity],x;

for(x=0;x<a.length;x++){
    console.log(a[x],(isNaN(+a[x]) || Math.round(+a[x]) != +a[x] || +a[x] === null || +a[x]+1==+a[x])?false:true);
}

If you run that in a console, it shows true for any element in a which would pass the validation, false otherwise. 如果您在控制台中运行该命令,则它对将通过验证的任何元素显示为true,否则为false。 This validation works as expected for me in Chrome ( false is shown for all decimals, and everything from undefined onward. 此验证在Chrome中符合我的预期(所有小数点都显示为false ,从未undefined所有内容开始显示。

My question is, will this work in all major browsers (IE 6+ included), and have I completely checked this against every possible input? 我的问题是,此功能是否可以在所有主流浏览器(包括IE 6+)中使用,并且我是否已针对所有可能的输入进行了全面检查?

As a note: 注意:

  • + is used in front of the a[x] for type-converting (and also trimming strings - " 2 " gets converted to 2 . +a[x]前面用于类型转换(以及修剪字符串- " 2 "转换为2

  • The last check, +a[x]+1===+a[x] is what checks against (+/-)Infinity . 最后一个检查+a[x]+1===+a[x]是检查(+/-)Infinity

Thanks :) . 谢谢 :) 。

Try this function 试试这个功能

function is_int(value){
   if((parseFloat(value) == parseInt(value)) && !isNaN(value)){
      alert("Is an Integer");
     } else {
      alert("Is not an Integer");
     }
   }

is_int(1); //Output - Is an Integer
is_int("a"); //Output - Is not an Integer

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM