[英]Using a regular expression to validate whether input has any non digits in it
function validInteger(theNumber){
var anyNonDigits = new RegExp('\D','g');
if(parseInt(theNumber)&&!anyNonDigits.test(theNumber)){
return true;
}else{
return false;
}
}
Above is a function I've written to validate some input. 以上是我为验证一些输入而编写的函数。 I want all positive integers.
我想要所有正整数。 The problem I'm facing is with the RegExp object.
我面临的问题是使用RegExp对象。 This seems like it should be super simple, but for some reason it's not working.
这似乎应该是超级简单的,但由于某种原因,它不起作用。
For example if I pass 'f5' I get true, but if I pass '5f' I get false. 例如,如果我通过'f5',我会得到真的,但如果我通过'5f',我就会变错。 I'm also having problems when passing negative numbers.
传递负数时我也遇到了问题。 -3 doesn't get caught even if I stringify the variable before passing it into the RegExp.
即使我在将变量传递给RegExp之前对变量进行了字符串化,-3也不会被捕获。 I can fix this by adding '
&&parseInt(theNumber)>0
' in my if statement, but I feel like the RegExp should catch that too. 我可以通过在if语句中添加'
&&parseInt(theNumber)>0
'来解决这个问题,但我觉得RegExp也应该抓住它。 Thanks in advance! 提前致谢!
Simply: 只是:
function validInteger(theNumber){
return theNumber.match(/^\d+$/) && parseInt(theNumber) > 0;
}
Or even simpler with regex
only as suggested by @Eric: 或者甚至更简单,正如@Eric所建议的
regex
:
return /^[0-9]\d*$/.test(theNumber);
Update: 更新:
An excellent cheat sheet. 一个优秀的备忘单。 The link died after 5 years, sorry. 该链接在5年后死亡,对不起。
If it's okay don't use RegExp, you can have: 如果没关系,请不要使用RegExp,您可以:
function validInteger(theNumber){
var number = +theNumber;
return number > -1 && number % 1 === 0;
}
Assuming that you consider 0 as positive integer, and you don't want to make a distinction between +0 and -0. 假设您将0视为正整数,并且您不希望区分+0和-0。
Notice that this function will accept any value for theNumber
that can be converted in a Number, so not just "string", and you can pass Number as well of course. 请注意,此功能将接受任何值
theNumber
可在数转换,所以不只是“串”,你可以通过数量以及课程。
Be simple! 简单!
function validate(num){
return (num | 0) > 0;
};
This function will return "true" only for positive integers. 此函数仅对正整数返回“true”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.