检查字符串是否为整数
我想验证输入字段。用户应输入长度至少为 10 位数字的电话号码。
所以我需要检查非法字符。最好只是检查输入是否是整数。
我想出了这个,但它不起作用(n 是字符串)。
function isInt(n){
return typeof n== 'number' && n%1==0;
}
有什么想法吗?
I want to validate a input field. The user should type in a phone number with minimum length of 10 digits.
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).
function isInt(n){
return typeof n== 'number' && n%1==0;
}
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以进行如下测试:
如果字符串中包含非数字或字符串长度小于 10 个字符,则测试将失败
You can do a test like this:
That will fail if there are non-digits in the string or the string is less than 10 chars long
这应该有效(
(input - 0)
自动尝试将值转换为数字):关于此问题已经有一个 SO 问题:在 JavaScript 中验证十进制数字 - IsNumeric()
This should work(
(input - 0)
automatically tries to convert the value to a number):There is already an SO-question about this issue: Validate decimal numbers in JavaScript - IsNumeric()
对您来说可能有点大材小用,但 Google 不久前发布了一个用于手机验证的库 。 Java 和 Javascript 变体可用。
Might be an overkill for you, but Google has not too long ago announced a library for phone validation. Java and Javascript variants are available.
验证电话号码比检查输入是否为整数稍微复杂一些。例如,电话号码可以并且确实以零开头,因此从技术上讲它不是整数。用户也可以输入破折号:例如:
因此,对于验证它,您有几个选项:
使用正则表达式进行验证,看看:
http://regexlib.com/
这个网站将有数百个示例
使用循环依次检查每个字符,即字符 int 或破折号
,因为后者取决于用户的一致输入,而你不会得到这个
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:
So, as for validating it you have a couple of options:
Use regex expression to validate, have a look at:
http://regexlib.com/
this site will have hundreds of examples
Use looping to check each characters in turn, i.e. is character int or dash
I would recommend the former as the latter depends on consistent input from users and you aren't going to get that
为什么不使用:
return (+val === ~~val && null !== val);
作为函数中的 return ?
这是 javascript 控制台的输出
Why not use:
return (+val === ~~val && null !== val);
as a return in your function?
this is the output of the javascript console