Javascript 使用正则表达式验证输入中是否有任何非数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10936293/
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-24 03:38:25  来源:igfitidea点击:

Using a regular expression to validate whether input has any non digits in it

javascriptregexvalidationintegerexpression

提问by Frank B

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. This seems like it should be super simple, but for some reason it's not working.

以上是我编写的用于验证某些输入的函数。我想要所有正整数。我面临的问题是 RegExp 对象。这看起来应该非常简单,但由于某种原因它不起作用。

For example if I pass 'f5' I get true, but if I pass '5f' I get false. 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. I can fix this by adding '&&parseInt(theNumber)>0' in my if statement, but I feel like the RegExp should catch that too. Thanks in advance!

例如,如果我通过 'f5' 我得到真,但如果我通过 '5f' 我得到假。我在传递负数时也遇到问题。即使我在将变量传递到 RegExp 之前对其进行字符串化,-3 也不会被捕获。我可以通过&&parseInt(theNumber)>0在 if 语句中添加 ' '来解决这个问题,但我觉得 RegExp 也应该捕获它。提前致谢!

回答by gdoron is supporting Monica

Simply:

简单地:

function validInteger(theNumber){    
    return theNumber.match(/^\d+$/) && parseInt(theNumber) > 0;
}

Live DEMO

现场演示

Or even simpler with regexonly as suggested by @Eric:

或者甚至更简单,regex仅按照@Eric 的建议:

return /^[0-9]\d*$/.test(theNumber);

Live DEMO

现场演示

Update:

更新:

An excellent cheat sheet.The link died after 5 years, sorry.

一个优秀的备忘单。该链接在 5 年后失效,抱歉。

回答by ZER0

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 theNumberthat can be converted in a Number, so not just "string", and you can pass Number as well of course.

请注意,此函数将接受theNumber可以转换为数字的任何值,因此不仅仅是“字符串”,您当然也可以传递数字。

回答by sgmonda

Be simple!

简单点!

function validate(num){
    return (num | 0) > 0;
};

This function will return "true" only for positive integers.

此函数将仅对正整数返回“true”。