javascript 检查字符串是否为整数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4691868/
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
Check string for integer
提问by Upvote
I want to validate a input field. The user should type in a phone number with minimum length of 10 digits.
我想验证输入字段。用户应输入至少 10 位数字的电话号码。
So I need to check for illegal chars. It would be nice just to check wheather the input is an integer or not.
所以我需要检查非法字符。只需检查输入是否为整数就好了。
I came up with this but it does not work (n would be the string).
我想出了这个,但它不起作用(n 将是字符串)。
function isInt(n){
return typeof n== 'number' && n%1==0;
}
Any ideas?
有任何想法吗?
回答by Martin Jespersen
You can do a test like this:
你可以做这样的测试:
input.length >= 10 && /^[0-9]+$/.test(input)
That will fail if there are non-digits in the string or the string is less than 10 chars long
如果字符串中有非数字或字符串长度小于 10 个字符,这将失败
回答by Tim Schmelter
This should work((input - 0)automatically tries to convert the value to a number):
这应该有效((input - 0)自动尝试将值转换为数字):
function isInt(input){
return ((input - 0) == input && input % 1==0);
}
There is already an SO-question about this issue: Validate decimal numbers in JavaScript - IsNumeric()
关于这个问题已经有一个 SO-question: Validate decimal numbers in JavaScript - IsNumeric()
回答by MrEyes
Validating a phone number is a little more complicated than checking if the input is an integer. As an example phone numbers can and do begin with zeros so it isn't technically and int. Also users may enter dashes: For example:
验证电话号码比检查输入是否为整数要复杂一些。例如,电话号码可以并且确实以零开头,因此从技术上讲它不是整数。用户也可以输入破折号:例如:
00 34 922-123-456
So, as for validating it you have a couple of options:
因此,至于验证它,您有几个选择:
Use regex expression to validate, have a look at:
this site will have hundreds of examples
Use looping to check each characters in turn, i.e. is character int or dash
使用正则表达式来验证,看看:
该站点将有数百个示例
使用循环依次检查每个字符,即字符是int还是dash
I would recommend the former as the latter depends on consistent input from users and you aren't going to get that
我会推荐前者,因为后者取决于用户的一致输入,而您不会得到它
回答by darioo
回答by papas-source
Why not use:
为什么不使用:
return (+val === ~~val && null !== val);
return (+val === ~~val && null !== val);
as a return in your function?
作为你函数的回报?
this is the output of the javascript console
这是 javascript 控制台的输出
> +"foobar" === ~~"foobar"
false
> +1.6 === ~~1.6
false
> +'-1' === ~~'-1'
true
> +'-1.56' === ~~'-1.56'
false
> +1 === ~~1
true
> +-1 === ~~-1
true
> +null === ~~null // this is why we need the "&& null !== val" in our return call
true

